I have stumbled on strange behaviour of lua. Code example:
function foo()
local t = {'a', 'b', 'c'}
return unpack(t)
end
function bar()
local t = {'x', 'y'}
return unpack(t)
end
b = { foo(), bar() }
for k,v in pairs(b) do
print(k,v)
end
Result of this code is:
1 a
2 x
3 y
So, results from foo() are all discarded except the first element. Question is, why some elements are discarded?
I have briefly checked lua 5.2 manual, but I don't see explanation for this behaviour.
Question is, why some elements are discarded?
Because that's how Lua works. Expressions that result in multiple values (function calls and ...), when used in the context of a list of things (such as a table constructor or a function call argument list) will only add all of their values to that list if it is the last element of the list.
So:
{foo, ...}
Will put all of the varargs at the end.
{..., foo}
Will only put the first of the varargs into the table.
If you want to bundle multiple function calls like this, you have to use a function that will table.insert each element into the list individually.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With