Lua - Get Entries from 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 - Adding entry to the table
Consider the example shown below −
main.lua
-- initialize an empty array
t = {}
-- add values to the array
t[1] = 1
t[2] = 2
t[3] = 3
t[4] = 4
-- print length of the array
print(#t)
Output
When we run the above code, we will get the following 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 - Adding mixed data to table
Consider the example shown below −
main.lua
-- initialize an empty array
t = {}
-- add values to the array
t["yes"] = 1
t[1] = 1
t[2] = 2
t[3] = 3
-- print length of the array
print(#t)
Output
When we run the above code, we will get the following 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 - Computing length of table
Consider the code shown below −
main.lua
-- initialize an empty array
t = {}
-- add values to the array
t["yes"] = 1
t[1] = 1
t[2] = 2
t[3] = 3
-- print length of the array
print(#t)
-- function to compute length of table
function tablelength(T)
local count = 0
for _ in pairs(T)
do
count = count + 1
end
return count
end
-- print length of the table
print(tablelength(t))
Output
When we run the above code, we will get the following output−
3 4