For Loop Not Looping Through Entire Table

My for loop doesn’t loop through my table and I’m not exactly sure why it is doing this.

This is the table I am using,

itemHandler.itemList = {
	[1] = {
		['ItemName'] = 'Wood',
		['ItemId'] = 1
	},
	[2] = {
		['ItemName'] = 'Leaves',
		['ItemId'] = 2
	},
	[3] = {
		['ItemName'] = 'Stone',
		['ItemId'] = 3
	}
}

And this is the code that loops through the table.

local function checkItem(itemId, list) 
	for _, item in ipairs(list) do
		print(item, itemId)
		if item['ItemId'] == itemId then
			return true
		else
			return false
		end
	end
end

This shows am image of what the table would look like printed. The 2 in the line 88 is the Item Id or iteration it should be at. The script only returns the first iteration of the table.

image

The function stops at the first entry of the table and I can’t get it to iterate past this. Is there any way I can? How would I be able to do it if there is?

Try removing ipairs, and/or also try removing the explicit indexes, like so:

itemHandler.itemList = {
	{
		['ItemName'] = 'Wood',
		['ItemId'] = 1
	},
	{
		['ItemName'] = 'Leaves',
		['ItemId'] = 2
	},
	{
		['ItemName'] = 'Stone',
		['ItemId'] = 3
	}
}
local function checkItem(itemId, list) 
	for _, item in list do
		print(item, itemId)
		if item['ItemId'] == itemId then
			return true
		else
			return false
		end
	end
end

This still returns the same thing.

image

It is because you are returning the function before it can loop through everything in the table.

local function checkItem(itemId, list) 
	for _, item in ipairs(list) do
		print(item, itemId)
		if item['ItemId'] == itemId then
			return true
		end
	end
	return false
end

i hope i understood the problem correctly but im assuming you want to print both index’s on separate lines, for this you shouldn’t need a for loop

you can do something like this

function checkItem(index, list)
    local item = list[index]

    print("Item Name" .. item['ItemName'])
    print("Item ID" .. item['ItemId'])
end

hope this solves your issue

This worked, thank you.
I can’t believe I was that dumb.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.