25

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?

2
  • 1
    Read for some information on multiple return values in Lua: lua.org/manual/5.2/manual.html#3.4 Commented Oct 9, 2012 at 20:49
  • This link will take you to the Lua-wiki page explaining exactly your problem. 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. Commented Dec 26, 2017 at 21:34

3 Answers 3

34

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
Sign up to request clarification or add additional context in comments.

3 Comments

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 stackoverflow.com/questions/1410862/… vs stackoverflow.com/questions/1283388/lua-merge-tables
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
Can I use the result of unpack as the params to another function? If so, what's the syntax?
19
...
function test3()
    local var1, var2 = test()
    return var1, var2, 3
end

print(test3())

2 Comments

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!
shouldn't you remove end at the return var1, var2, 3 ? It produces syntax error
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.