Search code examples
lua

How to get number of entries in a Lua table?


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?


Solution

  • You already have the solution in the question -- the only way is to iterate the whole table with pairs(..).

    function tablelength(T)
      local count = 0
      for _ in pairs(T) do count = count + 1 end
      return count
    end
    

    Also, notice that the "#" operator's definition is a bit more complicated than that. Let me illustrate that by taking this table:

    t = {1,2,3}
    t[5] = 1
    t[9] = 1
    

    According to the manual, any of 3, 5 and 9 are valid results for #t. The only sane way to use it is with arrays of one contiguous part without nil values.