How to get the number of entries in a Lua table?


While there are many functions and operators that we can use to get the size of the integer entries in a particular table in lua, there's no defined method or function which works for a table that contains data that is not homogeneous in nature.

Let’s consider a simple table where we have integer values stored in it, then we will use two most common approaches to find the number of entries in that table.

Example

Consider the example shown below −

 Live Demo

t = {}
t[1] = 1
t[2] = 2
t[3] = 3
t[4] = 4
print(#t)

Output

4

But let’s take the case where instead of having the homogenous data in the table, the data is not of the same type, then in that case the # operator will result in inconsistency.

Example

Consider the example shown below −

 Live Demo

t = {}
t["yes"] = 1
t[1] = 1
t[2] = 2
t[3] = 3
print(#t)

Output

3

As we can clearly see, that the output yields an inconsistency, hence we have no choice but to write our own function to calculate the number of entries present in the table.

Example

Consider the code shown below −

 Live Demo

t = {}
t["yes"] = 1
t[1] = 1
t[2] = 2
t[3] = 3
print(#t)
function tablelength(T)
   local count = 0
   for _ in pairs(T) do count = count + 1 end
   return count
end
print(tablelength(t))

Output

3
4

Updated on: 19-Jul-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements