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

假设我有以下三个函数:

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,就像手册所说:

print(foo2(), 1) --> a 1

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

foo2 函数出现在一个表达式中时,Lua 会调整返回值的数量;所以,在最后一行中,只有 "a" 在串联中使用。

问题是:有没有方法可以以一种简洁的方式从上面的调用中获得 getVector2D 的多个值,并期望结果为 66.0 77.0 88.0

点赞
用户2328287
用户2328287

我认为没有这样的方式。

最简单的方法是使用变量 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 函数。

2014-04-15 09:33:52
用户1208078
用户1208078

你可以使用临时表来保存参数并追加额外的参数?

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
2014-04-15 14:48:55