如何在 Lua 中直接访问具有多个输出的函数的第 n 个输出

How to directly access the n'th output of a function with multiple outputs in Lua

在 Python 中,可以执行以下操作并访问所需的函数输出:

getNthOutput = myFunc(args)[0] #Will get you the first output of a multi-output function in Python

如何在 Lua 中做同样的事情?下面是我的尝试,它给了我一个错误:

getNthOutput = myFunc(args)[1] --Get me the first output of a multi-output function in Lua

如果您只想要第一个 return 值(根据您的示例),您可以这样做:

first = myFunc(args)

如果你想要一个任意的 return 值,你可以使用 table 构造函数:

function myFunc()
    return 1, 2, 'a', 'b'
end

first = ({myFunc()})[1]
print(first)
# 1

n = 4
nth = ({myFunc()})[n]
print(nth)
# b

您收到错误消息,因为多个 return 值未 return 编辑为 table。因此,您无法使用 [].

访问任何 table 成员

较新的 Lua 版本提供了一个功能,可以将 return 值安全地放入 table 中,以便您以后可以使用它们的索引。

local retVals = table.pack(foo())
local firstValue = retVals[1]

或者干脆

table.pack(foo())[1]

在旧的 Lua 版本中没有函数 table.pack,但您可以简单地使用可变参数函数自己实现一个

function myPack(...)
  return {...} -- this only works since Lua 5.1
end

我不希望您使用 5.1 之前的版本。但是请注意可变参数函数的工作方式不同。请参阅有关函数定义

的相应 Lua 参考