syntax.us Let the syntax do the talking
Blog Contact Posts Questions Tags Hire Me

Question:
In Lua how to count table elements?

In old versions of Lua I counted number of elements in a table with table.getn(mytable).

Now, getn() has been replaced by the '# operator':
print(#mytable)
This operator works well on integer indexed tables.

For a key-indexed table, I need to count using a for-loop:
# ~/ks/b/lua/table_getn.lua

tab1 = {1,2,3,4}

-- n = table.getn(tab1)

-- getn() does not work in lua 5.3

-- this works, it returns number of elements:
print(#tab1)
-- We refer to # as the '# operator'

-- this fails:
tab2 = {k1 = 1, k2 = 2, k3 = 3}
print(#tab2)

-- this works:
ii = 0
for k,v in pairs(tab2) do
  ii = ii+1
end
print(ii)


syntax.us Let the syntax do the talking
Blog Contact Posts Questions Tags Hire Me