Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Does table.insert require an index?

I've been making loot drops and I received the following error: Wrong number of arguments to 'insert'

ServerScript:

function getItem(ID)
	local items = game:GetService("ServerStorage").Items:GetDescendants()
	for i, v in pairs(items) do
		if v:FindFirstChild("ItemID") then
			if v.ItemID.Value == ID then
				return v
			end
		end
	end
end

function dropItems(mob)
	local loot = {}
	for i, v in pairs(mob.MobConfig.ItemsDropped:GetChildren()) do
		local probability = math.random(1, 100)
		if v.Value >= probability then
			table.insert(loot, getItem(v.Name))			--Error occurs here
		end
	end
	return loot
end

Is there something trivial that I messed up on? Does table.insert need an index? Any help would be appreciated.

3 comments

1

I believe the issue is that the getItem function is returning a nil value. This errors most likely happens because you've put in a function inside the second argument to get the "item". Try making a variable with the function, and for the second argument in line 17 use that variable.

0

Yup. There was an error with the getItem function because I was comparing an integer with a string, returning nil. So, maybe the game thought that I was inserting an object at index nil. I fixed it by using tonumber(ID).

0

Glad I could help!

1 answer

✓ Accepted answer

As I've already answered the question in the comments, for anyone else receiving the same error (Wrong number of arguments to 'insert')

While passing a nil variable is allowed, passing a nullary function is not. Make sure your function does not return nil or just use a variable for the second argument of table.insert

This discussion is preserved as it was. New answers, comments, and votes are closed.