miércoles, 21 de mayo de 2014

multiple value return in lua

Lua functions can return multiple values, and the language will natively assign them to the variables on the other side of the equal sign.

local a, b = (function() return 1,2 end)()
print(a,b) => 1     2
That's fine, but when things get a bit more tricky is when the values are not returned in tail call position.
local a, b = (function()
               local res = (function() return 1 , 2 end)()
               return res
             end)()
print(a, b) =>  1    nil
The catch is that lua assigns the 'rest' of the values only to the last element of tables, or argument lists. If we want to wrap a function into another while not being in tail position, we have to use a little trick. This trick is unpack.
local a, b = (function()
               local res = {(function() return 1 , 2 end)()}
               return unpack(res)
             end)()
print(a, b) =>  1    2

No hay comentarios: