Reputation: 22460
Is there a way to pass a tuple as the parameters of a Lua function?
For example, I have a function that returns multiple values
function f(a,b) return b,a end
and I want this function f
to be repeatedly applied, so I can write:
f (f ... f(1,2))
But what if I need to store this initial tuple (1,2)
as a variable init
?
f (f ... f(init))
Is there support for this?
According to this answer, it seems python has it with the splat operator *
.
Upvotes: 6
Views: 21149
Reputation: 473182
Lua does not have "tuples".
When a function returns multiple values, it returns multiple values. They aren't put together into some data structure; they're separate values. If you want to store multiple return values in a single data structure, you have to actually do that.
Lua 5.2 has the table.pack
function, which you can use to store multiple return values in a table. But it does so in such a way that you can decompose them later:
local values = table.pack(f(1, 2))
f(table.unpack(values, values.n))
unpack
exists in Lua 5.1, but pack
does not. You can emulate it easily enough:
function pack(...)
return {n = select("#", ...), ...}
end
Upvotes: 12