如何优雅地在Lua中引用多返回值函数中的返回值?

假设我有一个函数:

function func()
    return 1, 2, 3
end

是否有一种优雅的方法引用每个返回值?例如

if func() == 1 then
  print(“stuff”)
end

但是引用第二或第三个返回值?

我知道你可以这样做

if ({func()})[2] == 2 then ...

但这看起来很糟糕,与其这样不如

_,v = func()
if v == 2 then ...

我想做一些像这样的事情

if func() == _,2 then ...
点赞
用户573255
用户573255

这就是 select 的使用方法:

if select(2, func()) == 2 then ... end

print(select(1, func()) -- 输出 1 2 3
print(select(2, func()) -- 输出 2 3
print(select(3, func()) -- 输出 3
print(select('#', func()) -- 输出 3,接收到的参数总数
2019-01-03 20:20:45