table.unpack() only returns the first element [duplicate]
Asked Answered
M

2

16

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

Here is some demo 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 don't understand why the second line just prints 1 Test. I'd expect it to print 1 2 3 4 5 Test. Can somebody explain this behaviour? I'd also be interested in how I can make the second call to print 1 2 3 4 5 Test.

Munitions answered 7/9, 2015 at 13:16 Comment(3)
I've asked the same question before: #29892579Syblesybley
See edit. I was also asking for a workaround.Munitions
See here to know where all a list of expressions can occur in Lua.Align
Q
21

table.unpack returns multiple values. The defined behavior in that case is that if it is not the last one in a list of expressions then all but the first returned 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 a statement, Lua discards all of its results. When we use a call as an expression, Lua keeps only the first result. We get all results only when the call is the last (or the only) expression in a list of expressions.

As a workaround you can append the rest of the arguments to the table and make the table the last argument that way.

Quad answered 7/9, 2015 at 13:25 Comment(2)
I'm glad you found the quote from the docs. :)Zeke
Me too, I have read it just a few months ago... :)Quad
Z
5

table.unpack() is returning the same thing in either case, but in the second case Lua is only expecting one value so it isn't going to turn it into multiple arguments. When it is the last argument Lua is ok with it turning into multiple arguments.

Zeke answered 7/9, 2015 at 13:23 Comment(4)
Thanks. So I guess there is no way to make the second call return "1 2 3 4 5 Test"?Munitions
@Munitions We get all results only when the call is the last (or the only) expression in a list of expressions. sounds pretty clear, in the other answer.Pneumato
Yes, I know, I just asked because maybe there was a trick or something to workaround this behaviour :)Munitions
@Andreas: appending to the table before unpacking it as one might work for you.Quad

© 2022 - 2024 — McMap. All rights reserved.