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