"#Table" returns 0 even tho theres more than 0 things in a table

#PlacementModule.Blocks.Generator” returns 0

here is the table in question:

module.Blocks = {
	Generator = {
		Basic = {
			ID = 1,
			Color = module.GenColor("Basic"),
			-- blah blah blah
		},
	},
}

it should return 1… theres 1 thing in the Blocks.Generator table, its the Basic Table
im confused, someone help me out here please

“#” operator doesn’t work for dictionaries

ok then how do I get the amount of things in the table in this case

You could perchance do a for loop.

i.e

local counter = 0
for i,v in pairs(...) do
      counter += 1
end

It goes as easy as incrementing an int value each time a value gets iterated on using “pairs”.

yes and no
in lua you can mix dictionary keys with array keys
#Table ignores all the dictionary keys

print(#{
    One = 2,
    5,
    6,
    7,
    Two = 10
})

this will print out 3 because it ignores the 2 dictionary keys

1 Like

You can also set __len metamethod to sum the number of elements for you when # is used on a table. And it’s even possible reuse the same metatable for multiple dictionaries:

local lenMt = {
	__len = function(self)
		local sum = 0
		for k,v in self do
			sum += 1
		end
		return sum
	end;
}

local t = setmetatable({}, lenMt)
local t2 = setmetatable({}, lenMt)
t.key1 = 1; t.key2 = 2
t2.key1 = 1; t2.key2 = 2; t2.key3 = 3
print(#t, #t2) --> 2, 3
1 Like

ehhhhhhhhhhhhhhhhhhhhhh too much work :skull_and_crossbones: :skull_and_crossbones: :pray: :sob: :sob:

1 Like

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