多个结果作为函数中参数的一部分

时间:2014-04-15 07:53:04

标签: lua

假设我有这三个功能:

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)

期望(和获得的)结果仅从x进行getVector2D评估,正如the manual所说:

  

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

     

当表达式中出现对foo2的调用时,Lua会将结果数调整为1;所以,在最后一行,只有" a"用于连接。

问题是:有没有办法在上面的调用中从getVector2D获取多个值,并希望结果是干净的66.0 77.0 88.0

2 个答案:

答案 0 :(得分:2)

我认为没有这样的方式。

最简单的方法是使用变量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库中也作为vararg.append函数存在。

答案 1 :(得分:1)

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

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