table.unpack() function in Lua programming

LuaServer Side ProgrammingProgramming

When we want to return multiple values from a table, we make use of the table.unpack() function. It takes a list and returns multiple values.

Syntax

table.unpack{x,y,z,....}

Example

The table.unpack() function provides us with all the values that are passed to it as an argument, but we can also specify which value we want by following the example shown below −

 Live Demo

a, b = table.unpack{1,2,3}
print(a, b)

In the above example, even though the table.unpack() function contains different values, namely 1, 2 and 3, we only are storing the first two values, i.e., a and b and the value 3 will be discarded.

Output

1 2

Example

It should be noted that if we don’t pass any value then all the values that are present in the list will be returned from the table.unpack() function. Consider the example shown below −

 Live Demo

print(table.unpack{1,2,3})

Output

1   2   3

Example

We can also ignore elements and select a specific index or positioned element from the list, consider the example shown below −

 Live Demo

_, b = table.unpack{-1,-2}
print(b)

Output

-2
raja
Published on 19-Jul-2021 11:16:50
Advertisements