Table.unpack () returns only the first item

Can someone explain to me why table.unpack() returns the first element of the table only when it is used in a function call with additional parameters after table.unpack() ?

Here is the daemon code:

 local a = {1,2,3,4,5} print("Test", table.unpack(a)) -- prints "Test 1 2 3 4 5" print(table.unpack(a), "Test") -- prints "1 Test" 

I do not understand why the second line just prints 1 Test . I expect it to print 1 2 3 4 5 Test . Can anyone explain this behavior? I will also be interested in how to make a second call to print 1 2 3 4 5 Test .

+8
lua-table lua
source share
2 answers

table.unpack returns multiple values. The specific behavior in this case is that if it is not the last in the list of expressions, then all but the first return value will be discarded.

From the book :

Lua always adjusts the number of results from a function to the circumstances of the call. When we call a function as an instruction, Lua discards all its results. When we use the call as an expression, Lua only saves the first result. We get all the results only when the call is the last (or only) expression in the list of expressions.

As a workaround, you can add the remaining arguments to the table and make the table the last argument in this way.

+9
source share

table.unpack() returns the same thing anyway, but in the second case, Lua expects only one value, so it is not going to turn it into multiple arguments. When this is the last argument, Lua is fine, turning it into multiple arguments.

+4
source share

All Articles