How do I get the number of keys in a hash table in Lua?
问题 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 回答1: 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