【问题标题】:How do I store all results from a function into a single variable in Lua?如何将函数的所有结果存储到 Lua 中的单个变量中?
【发布时间】:2018-06-07 14:46:02
【问题描述】:

我有

function foo()
    return a, b
end
x, y = foo() -- x == a, y == b
z = foo() -- z == a

有没有更简单的方法将ab(以及函数中的任何其他变量)作为数组传输到z

z = {} 初始化z 不起作用,因为它只是将它重新定义为foo() 的第一个结果。

【问题讨论】:

    标签: arrays function lua


    【解决方案1】:

    怎么样:

    -- define the function
    function foo()
        return "one", "two"
    end
    -- set z to a table of the return values of foo().  The first return
    -- value will be z[1], the second one z[2], and so on.
    z = {foo()}
    -- print it out
    for k,v in pairs(z) do
        print(k, v)
    end
    

    应该得到

    1   one
    2   two
    

    这就是你要找的东西吗?

    【讨论】:

    • 我不知道pairs 做了什么,但我不需要。我以不同的方式处理z。这行得通。谢谢。
    • 不客气。而且你很快就会爱上pairs()(它超级方便)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-02
    • 2018-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-27
    相关资源
    最近更新 更多