Lua:任意数量的返回值



在学习了很长一段时间的C++之后,我将回到Lua,目前我正试图再次了解一些更复杂的事情。

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

-- 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足够有效,并且它不会主要影响此类调用的总体执行时间。

最新更新