简体   繁体   中英

How to pass a tuple as arguments to a Lua function?

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 * .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM