23

I am experimenting with the following lua code:

function test() return 1, 2 end
function test2() return test() end
function test3() return test(), 3 end

print(test()) -- prints 1 2
print(test2()) -- prints 1 2
print(test3()) -- prints 1 3

I would like test3 to return 1, 2, 3

What is the best way to achieve this?

Kara
  • 6,115
  • 16
  • 50
  • 57
  • 1
    Read for some information on multiple return values in Lua: http://www.lua.org/manual/5.2/manual.html#3.4 – Alex Oct 09 '12 at 20:49
  • This link will take you to the Lua-wiki page explaining exactly your problem. https://www.lua.org/pil/5.1.html Lua is programmed to only return the first value of `test()` if it is being returned with another value. – GreenHawk1220 Dec 26 '17 at 21:34

3 Answers3

31

you could do something like this if you aren't sure how many values some function may return.

function test() return 1, 2 end
function test2() return test() end
function test3()
    local values = {test2()}
    table.insert(values, 3)
    return unpack(values)
end


print(test3())

this outputs:

1   2   3
Mike Corcoran
  • 14,072
  • 4
  • 37
  • 49
  • What if I wanted to `return test(), test()` - I get `1 1 2`. Probably I would need to catch each "tuple" with `{ }`, and then concatenate* (not "merge") them here. (*) - see http://stackoverflow.com/questions/1410862/concatenation-of-tables-in-lua vs http://stackoverflow.com/questions/1283388/lua-merge-tables – Tomasz Gandor Oct 19 '16 at 07:43
  • yes, `return test(), test()` is just a slightly diff. variant of the `return test(), 3` example in the OP. a far better explanation than I could give is located on [this programming in lua document](https://www.lua.org/pil/5.1.html) – Mike Corcoran Nov 07 '16 at 20:48
  • Can I use the result of `unpack` as the params to another function? If so, what's the syntax? – NeoZoom.lua Jan 17 '22 at 12:13
16
...
function test3()
    local var1, var2 = test()
    return var1, var2, 3
end

print(test3())
Derzu
  • 7,011
  • 3
  • 57
  • 60
Darkwater
  • 1,358
  • 2
  • 12
  • 25
  • 2
    In that case, it would be better to use a table. Having an unknown number of return values will quickly become very, very annoying to work with. If you use a table, you can simply unpack it _outside_ of the function: `print(table.unpack(testN())`, where `testN` returns some unknown number of return values, would print all of the return values! – T Suds Oct 10 '12 at 01:55
  • shouldn't you remove end at the return var1, var2, 3 ? It produces syntax error – Izzy Jan 20 '17 at 16:41
5

I have also found that with the function call at the end of the list the return values are not truncated. If order of the arguments does not matter this works well.

function test() return 1, 2 end
function test2() return test() end
function test3() return 3, test() end

print(test()) -- prints 1 2
print(test2()) -- prints 1 2
print(test3()) -- prints 3 1 2
Kara
  • 6,115
  • 16
  • 50
  • 57