Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua: passing multiple results from function to table constructor

Tags:

lua

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.

like image 738
pashkoff Avatar asked Dec 03 '25 17:12

pashkoff


1 Answers

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.

like image 166
Nicol Bolas Avatar answered Dec 06 '25 16:12

Nicol Bolas