【问题标题】:Multiple results as part of the arguments in a function多个结果作为函数参数的一部分
【发布时间】:2014-05-29 10:47:59
【问题描述】:

假设我有这三个函数:

function getVector2D()
    return 66.0, 77.0
end
 
function setVector2D(x, y)
    print(x.." "..y)
end

function setVector3D(x, y, z)
    print(x.." "..y.." "..z)
end

如果我使用setVector2D(getVector2D()),我没有问题,因为来自getVector2D 的多值返回将应用于setVector2D,结果将是66.0 77.0
但是,如果我想部分应用以下参数怎么办:setVector3D(getVector2D(), 88.0)

预期(和获得的)结果将仅是从getVector2D 评估的x,正如the manual 所说:

print(foo2(), 1) --> a 1
print(foo2() .. "x") --> ax (see below)

当对 foo2 的调用出现在表达式中时,Lua 会将结果数调整为 1;因此,在最后一行中,仅在连接中使用了“a”。

问题是:有什么方法可以在上面的调用中从getVector2D 获取多个值,并期望结果是66.0 77.0 88.0 干净的方式?

【问题讨论】:

    标签: lua


    【解决方案1】:

    我认为没有这种方法。

    最简单的方法是使用变量loaval z,x,y = 88.0, getVector2D()

    您可以使用代理功能:

    function proxy2D(t, z) return t[1],t[2],z end
    setVector3D(proxy2D({getVector2D()}, 88.0))
    

    function proxy2D(z, x, y) return x,y,z end
    setVector3D(proxy2D(88.0, getVector2D()))
    

    最后一个变体也作为vararg.append 函数存在于vararg 库中。

    【讨论】:

    • 您所指的 vararg 库在普通 Lua 中不可用。
    • vararg 库有 2 个实现 Lua 和 C。这是 Lua 版本github.com/moteus/lua-vararg/blob/master/vararg.lua
    • 是的,但它不是内置库。
    • 我明白了.. 我认为的唯一其他选择是将函数用于最后一个参数,例如A(1, B(2, 3)) 返回 1, 2, 3 其中 A 和 B 只返回它们的参数。
    【解决方案2】:

    您可以使用临时表来捕获参数并附加其他参数吗?

    function getVector2D()
        return 66.0, 77.0
    end
    
    function setVector2D(x, y)
        print(x,y)
    end
    
    function setVector3D(x, y, z)
        print(x,y,z)
    end
    
    local args = {getVector2D()}
    args[#args+1] = 88.0
    setVector3D(unpack(args))
    
    >> 66   77  88
    

    【讨论】:

      猜你喜欢
      • 2018-06-30
      • 1970-01-01
      • 2018-01-15
      • 2018-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-05
      • 1970-01-01
      相关资源
      最近更新 更多