How to get number of entries in a Lua table?

Posted by romkyns on Stack Overflow See other posts from Stack Overflow or by romkyns
Published on 2010-04-24T19:10:41Z Indexed on 2010/04/24 19:13 UTC
Read the original article Hit count: 156

Filed under:

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?

© Stack Overflow or respective owner

Related posts about lua