Returning multiple values from functions in lua

...
function test3()
    local var1, var2 = test()
    return var1, var2, 3
end

print(test3())

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

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

Tags:

Lua