"#Table" not returning proper value

The for loop is iterating through a table with tables inside it. I’m trying to catch the tables that aren’t empty with #v, but even though it iterated over a table that had more than 0 elements in it, it still printed as 0. Why is this?

Code

game.ReplicatedStorage.Inventory.MapInventory.OnClientEvent:Connect(function(Inventory)
	for i,v in pairs(Inventory.Data) do
		print(v)
		print(#v)
		end
end)

Output
image
Table has [“Bucket”] = 1, but after it still prints 0.

#Table only works when the Table is an array, not a dictionary. When it is a dictionary, it doesn’t count the elements.

Studio now warns people when you try it.
image


The only alternative I could find is having a loop over it and counting it up like this:

local Size = 0
for _, _ in pairs(Dictionary) do
	Size += 1
end
print(Size)

where Dictionary is the table you want to get the number of elements in, and Size is the total number of elements

2 Likes

Thank you for this. This is the final code I got to work

game.ReplicatedStorage.Inventory.MapInventory.OnClientEvent:Connect(function(Inventory)
	for i,v in pairs(Inventory.Data) do
		for a,b in pairs(v) do
			if b then
				print(v)
			end
		end
	end
end)

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