How to get number of entries in a Lua table?

Solution 1:

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.

Solution 2:

You can set up a meta-table to track the number of entries, this may be faster than iteration if this information is a needed frequently.

Solution 3:

The easiest way that I know of to get the number of entries in a table is with '#'. #tableName gets the number of entries as long as they are numbered:

tbl={
    [1]
    [2]
    [3]
    [4]
    [5]
}
print(#tbl)--prints the highest number in the table: 5

Sadly, if they are not numbered, it won't work.

Solution 4:

There's one way, but it might be disappointing: use an additional variable (or one of the table's field) for storing the count, and increase it every time you make an insertion.

count = 0
tbl = {}

tbl["test"] = 47
count = count + 1

tbl[1] = 48
count = count + 1

print(count)   -- prints "2"

There's no other way, the # operator will only work on array-like tables with consecutive keys.