Array Size in Lua Programming

LuaServer Side ProgrammingProgramming

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 with two functions to manipulate the size of the array and these are −

  • setn
  • getn

The setn function is used to set the size of the array explicitly and the getn is used to extract the size that was set by the setn.

How does it work under the hood?

Whenever we make a call to table.setn(t, n), then it associates t with n in an internal (weak) table and a call to table.getn(t) retrieves the value associated with t in that internal table.

If the table t has a field "n" with a numeric value, setn updates this value and then the getn returns it. The getn function still has a last option: If it cannot get an array size with any of those options, it uses the naive approach: to traverse the array looking for its first nil element. So, you can always use table.getn(t) in an array and get a reasonable result.

Let’s consider a few examples where we will first use the naive case, where we will make use of the setn and getn without the array having a field n.


--> 3
--> 2
print(table.getn{10,2,nil; n=3})
--> 3
--> 1000



Now let’s use the field n inside the array.


Consider the example shown below −

a = {n=10}
print(table.getn(a)) --> 10
table.setn(a, 1000)
print(table.getn(a)) --> 1000


Updated on 20-Jul-2021 13:52:36