How do I get the number of keys in a hash table in Lua?

Jay picture Jay · Mar 17, 2009 · Viewed 31.2k times · Source
myTable = {}
myTable["foo"] = 12
myTable["bar"] = "blah"
print(#myTable) -- this prints 0

Do I actually have to iterate through the items in the table to get the number of keys?

numItems = 0
for k,v in pairs(myTable) do
    numItems = numItems + 1
end
print(numItems) -- this prints 2

Answer

Aaron Saarela picture Aaron Saarela · Mar 17, 2009

I experimented with both the # operator and table.getn(). I thought table.getn() would do what you wanted but as it turns out it's returning the same value as #, namely 0. It appears that dictionaries insert nil placeholders as necessary.

Looping over the keys and counting them seems like the only way to get the dictionary size.