Nanfeng

Notes on software development, code, and curious ideas

Counting Fields in a Lua Table

The Lua # operator is intended for sequence-like tables with consecutive integer keys. It is not a general count of every field, especially when the table contains holes or string keys.

To count all entries whose value is not nil, iterate with pairs:

1
2
3
4
5
6
7
function table.nums(t)
local count = 0
for _ in pairs(t) do
count = count + 1
end
return count
end

For { "a", "b", "c" }, #t is appropriate. For { name = "Ada", score = 10 }, use an explicit loop such as table.nums(t).

+