【问题标题】:How to directly access the n'th output of a function with multiple outputs in Lua如何在Lua中直接访问具有多个输出的函数的第n个输出
【发布时间】:2016-07-26 03:29:42
【问题描述】:

在 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

【问题讨论】:

  • 在 Python 中,函数使用() 调用,而不是[]。您的示例应为:myFunc()[0]
  • @mhawke 对不起我的错。现在已经修复了

标签: python function lua return-value


【解决方案1】:

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

first = myFunc(args)

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

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

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

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

【讨论】:

  • 请注意,如果函数可以返回中间 nil 值,则表构造函数可能会出现问题。您需要 select 来稳健地处理它(以及正确使用它的函数)或在 lua 5.2+ 中使用 table.pack
【解决方案2】:

您收到一个错误,因为多个返回值没有作为一个表返回。因此,您无法使用[] 访问任何表成员。

较新的 Lua 版本提供了将返回值安全地放入表中的功能,以便您以后可以使用索引。

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

或者干脆

table.pack(foo())[1]

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

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

我不希望您使用 5.1 之前的版本。但请注意,可变参数函数的工作方式不同。请参阅函数定义上的相应 Lua 参考

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-26
    • 1970-01-01
    • 2013-05-06
    相关资源
    最近更新 更多