How to return several values from a function?

A Lua function can return multiple values:

function sumdiff(x,y)
 return x+y, x-y end local a,b = sumdiff(20,10)

Note a difference between Lua and Python; Python returns several values by packing them into a single tuple value, whereas Lua genuinely returns multiple values and can do this very efficiently. The assignment is equivalent to the multiple Lua assignment

local a,b = 30,10

If your function constructs an array-like table, then it can return the array values as multiple values with unpack.

Another way for a function to return values is by modifying a table argument:

function table_mod(t)
 t.x = 2*t.x
 t.y = t.y - 1
end t = {x=1,y=2}
table_mod(t)
assert(t.x==2 and t.y==1)

We can do this because tables are always passed by reference.



Back