Table.find not working properly

I’m working on an inventory system, i’m listing all the available items in items and the inventory example is inside structure (since in the future i may be storing inventory inside a table of player data).

the function add() works fine, but when running check() it says i don’t have the item. How would I fix this script to check for an item in the items table, and if it exists in the inventory, say that they have the item and state the name (as it’s inside the item in items).

local structure = {
	["Inventory"] = {
		
	},
	
}
local items = {
	["002930"] = {
		name = "Cool item",
	}
}

function add(item)
	table.insert(structure.Inventory, #structure.Inventory+1, item)
	print(structure.Inventory)
end
add("002930")
function check()
	for i = 1, #structure.Inventory do
		local item = structure.Inventory[i]
		if table.find(items, item) then
			print("has item")
			print("the item is called ".. item.Name)
		else
			print("doesn't have item")
		end
	end
	
end
1 Like

table.find() only works on arrays, not dictionaries. You would have to loop through the dictionary to and check it.

how would i go about implementing that?

So inside the loop for Inventory, loop through the items table and see if the item matches the item in the inventory.

By the way, instead of using a numerical loop, you can use a pairs loop.

for i, v in pairs(structure.Inventory) do
    -- code
end

With a pairs loop, v is structure.Inventory[i] so you do not have to make a new variable.

I don’t think he requires a generic for to check for the items - he could check if there’s an index for the item via the item variable.

if items[item] ~= nil then
    ...

Your Problem you didnt called the “Check” function…

Heres the working code.

Click For Code
    local structure = {
	["Inventory"] = {

	}

}
local items = {
	"002930"
}

function check()
	print("function called")
	for i = 1, #structure.Inventory do
		local item = structure.Inventory[i]
			if table.find(items, item) then
				print("has item")
				print("the item is called ".. item)
			else
				print("doesn't have item")
			end
		end
end

function add(item)
	table.insert(structure.Inventory, #structure.Inventory+1, item)
	wait(2)
	for i = 1, #structure.Inventory do
		print(structure.Inventory[i])
	end
	check()
end
add("002930")

image

that works perfectly to get the item 002930, but 002930 no longer has anything inside it. I’d like to store a name and maybe other data inside, so how would I check the dictionary for an id, and then print name if applicable.