Lua - Array Length



It is a general convention that the size of the array is the number of elements that are present inside the array before the nil. In many cases, nil is not allowed in the array, but for some applications, it is not an issue to have nil inside them.

If we allow nil values inside the array, then we must have some functions to set the size of the array explicitly.

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

# operator returns the size of the table which is numerically indexed. A table size is one less than first integer index with nil value. If table is having gaps in the sequence then table size is not gurranteed to be last gap. Lua follows binary search to find a gap and may not be the first or last one.

Example - Use of # Operator

main.lua

-- get length of array of three elements
print(#{10,2,4})
--> 3
-- get length of array of two elements, set last element as nil
print(#{10,2,nil})
--> 2
-- get length of array of two elements, set last element as nil
-- set size of array as 3
print(#{10,2,nil; n=3})
--> 2
-- get length of array of zero elements where size is 1000
print(#{n=1000})
--> 0

Output

When we run the above code, we will get the following output−

3
2
2
0

Example - Getting Length of String

Consider the example shown below −

main.lua

-- get length of array of 4 elements
n = # { "welcome", "to", "tutorialspoint", "com", name = "Mahesh" } --> 4
print(n)

-- get length of array of 4 elements
-- use # to get length of the array
n = # { "welcome", "to", "tutorialspoint", "com" } --> 4
print(n)

Output

When we run the above code, we will get the following output−

4
4
Advertisements