table.pack() function in Lua programming

LuaServer Side ProgrammingProgramming

When we want to return a table as a result from multiple values passed into a function, then we make use of the table.pack() function. The table.pack() function is a variadic function.

Syntax

table.pack(x,y,z,....)

Example

The table.pack() function provides a table formed with all the values that are passed to it as an argument, consider the example shown below −

 Live Demo

a = table.pack(1,2,3)
print(a)
print(a.n)

In the above example, we passed three numbers to the table.pack() function as an argument and then we are printing the returned value, i.e., which will hold the address of the table that contains the value that we passed as an argument and lastly we are printing the number of elements that are present in the table with the help of the n keyword.

Output

table: 0x13998b0
3

It should be noted that when we pass the values as an argument then an additional field in the table is added which is generally something like this −

{n = “number of elements in table”}

And then, we can use this n also. Now let’s use the generic for loop to print all the elements inside the table that were returned from the table.pack() function.

Example

Consider the example shown below −

 Live Demo

local a = table.pack(10,20,30)
for _, v in pairs(a) do print(v) end

Output

10
20
30
3

If we look closely at the output, we can clearly see that the last output number is basically the n that was added to the table by Lua.

We can also check the return type of the table that was returned by following the code shown below −

print(type(table.pack(1,2,3)))

Output

table
raja
Published on 19-Jul-2021 11:14:56
Advertisements