Lua - Get table size

By xngo on February 22, 2019

In lua, in order to get the table size, you have to manually write code to count each row.

local tbl = {"dog", "cat", "mouse", name="dolphin"}
 
-- To get the correct number of rows in a table, you have to manually count them.
count = 0
for _ in pairs(tbl) do count = count + 1 end
print(count)
 
 
-- Using # operator or table.getn() is not guaranteed. See examples below.
--  Both return 3 instead of 4 because 
--  table.getn() and # look for numeric indices; 
--  they won't see string indices.
--  Also, table.getn() was deprecated in 5.1 and will be removed in 5.2.
print("Table size using # operator = " .. #tbl)
print("Table size using table.getn() = " .. table.getn(tbl)) 

Refernce

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.