Sounds like a "let me google it for you" question, but somehow I can't find an answer. The Lua #
operator only counts entries with integer keys, and so does table.getn
:
tbl = {}
tbl["test"] = 47
tbl[1] = 48
print(#tbl, table.getn(tbl)) -- prints "1 1"
count = 0
for _ in pairs(tbl) do count = count + 1 end
print(count) -- prints "2"
How do I get the number of all entries without counting them?
dictionary[value] = #dictionary + 1
, where#
represents the number of all objects. What I wonder is why you don't want this: in all sane use cases for # (see answer by kaizer.se), the count of all objects is exactly equal to what # already returns; it seems like making # count everything is strictly an improvement. Of course I'm a Lua newbie and might be missing the point. – Dugongnext(t)~=nil and next(next(t))==nil
. – Canarese