Lua:任意数量的返回值 我在C++的很长一段时间后回到Lua,现在我正试图重新思考一些更复杂的事情。

Lua:任意数量的返回值 我在C++的很长一段时间后回到Lua,现在我正试图重新思考一些更复杂的事情。,lua,variadic-functions,Lua,Variadic Functions,想象一个小的实用函数,它看起来像这样,为任意数量的参数多次调用一个函数: -- helper to call a function multiple times at once function smartCall(func, ...) -- the variadic arguments local args = {...} -- the table to save the return values local ret = {} -- iterate o

想象一个小的实用函数,它看起来像这样,为任意数量的参数多次调用一个函数:

-- helper to call a function multiple times at once
function smartCall(func, ...)
    -- the variadic arguments
    local args = {...}
    -- the table to save the return values
    local ret = {}
    -- iterate over the arguments
    for i,v in ipairs(args) do
            -- if it is a table, we unpack the table
        if type(v) == "table" then
            ret[i] = func(unpack(v))
        else
            -- else we call the function directly
            ret[i] = func(v)
        end
    end
    -- return the individual return values
    return unpack(ret)
end
然后我可以这样做:

local a,b,c = smartCall(math.abs, -1, 2.0, -3.0)
local d,e,f = smartCall(math.min, {1.0, 0.3}, {-1.0, 2.3}, {0.5, 0.7})
这是可行的,但我想知道是否有更方便的方法,因为我的版本包含很多解包和临时表


ty

如果用C编写
smartCall
,它会更简单,并且不需要创建表。不过,我不知道这对您是否方便。

有一段时间,我考虑将所有内容作为字符串传递,然后操纵字符串以进行有效的函数调用,并使用
tostring调用它;就在那时,我意识到这根本不比在这里拆包更有效率

然后我考虑添加一个额外的参数,指定要智能调用的函数的参数数量。对于具有固定数量参数的函数,
smartCall
可以通过这种方式将其参数组传递给被调用的函数。同样,这一个需要提取表部分或算术来找到参数号


所以,我想不出任何更简单的函数。而且
unpack
足够有效,并且不会严重影响此类调用的总体执行时间。

嘿,我正在处理一些纯lua模块,这基本上是为了避免重写大量重复代码。但是由于它是用于向量数学的,我可能会忘记这个想法,而是编写重复的代码;如果返回更多,则忽略这些。你确定这就是你想要的吗?