Lua - Tables Length
Size of the Table is the number of elements that are present inside the table. In case of numerically sized table, we've Lua operator # to get the table size correctly.
Lua does provide us a function to get the size of numerically sized array −
#− used to get the size of numerically sized array.
Syntax
-- get the length of array using # operator n = # (t)
t− array
n− size of the array
Example - Size of Numerically Indexed Table
# operator returns the size of the numerically indexed table. A table size will be one less than first integer index with nil value. In case of non-numeric keys, behaviour of # operator is not certain. Consider the following code:
main.lua
-- initialize a table
table = { 1, 2, 3}
-- print the length of the table as 3
print(#table)
-- add a non-numeric key to the table
table["a"] = 4
-- print the length of the table as 3
print(#table)
-- set one entry as nil
table[2] = nil
-- print the length of the table as 0
print(#table)
Output
When you build and execute the above program, it produces the following result −
3 3 3
Example - Computing Correct Size using counting method.
We can count each element using a for loop in the table, and then get the size of it.
main.lua
-- initialize a table
table = { 1, 2, 3}
table["a"] = 4
local count = 0
for _ in pairs(table) do
count = count + 1
end
print(count)
Output
When you build and execute the above program, it produces the following result −
4
Example - Computing length of Table
Now let's encapsulate our counting logic within a function as len() and cover all the scenarios as discussed above in first example.
main.lua
function len()
local count = 0
for _ in pairs(table) do
count = count + 1
end
return count
end
-- initialize a table
table = { 1, 2, 3}
-- print the length of the table as 3
print(len(table))
-- add a non-numeric key to the table
table["a"] = 4
-- print the length of the table as 4
print(len(table))
-- set one entry as nil
table[2] = nil
-- print the length of the table as 2
print(len(table))
Output
When you build and execute the above program, it produces the following result −
3 4 3