【问题标题】:Lua function with arg pass to another function with arg带 arg 的 Lua 函数传递给带 arg 的另一个函数
【发布时间】:2015-11-10 03:51:11
【问题描述】:

这是我想要做什么的原始想法。

function a(str)
    print(str)
end

function b(str)
    print(str)
end

function c(str)
    print(str)
end

function runfunctions(...)
    local lst = {...}
    lst.startup()
end

local n1 = a('1')
local n2 = b('2')
local n3 = c('3')

runfunctions(n3,n1,n2)

很少有函数必须作为参数传递给其他函数并按顺序执行。一旦它们中的任何一个被执行,它就不能在毫秒内执行,所以 next 将被执行,以避免只执行其中的几个并且不要运行到最后一个。

【问题讨论】:

    标签: function lua


    【解决方案1】:

    你需要闭包。

    在您的代码中,函数abc 都执行并且不返回任何内容。相反,返回一个完成工作的闭包(但现在不执行):

    function a(str)
        return function() print(str) end
    end
    

    然后在需要的时候执行函数:

    function runfunctions(...)
        for _, v in ipairs{...} do
            v()
        end
    end
    

    【讨论】:

    • 当这些函数得到一些动作并且它们没有返回任何值时,会是什么样子呢?
    【解决方案2】:
    function runfunctions(...)
       for _, f_with_args in ipairs{...} do
          pcall((table.unpack or unpack)(f_with_args))
       end
    end
    
    runfunctions({c, '3'}, {a, '1'}, {b, '2'}, {print, "Hello", "world"})
    

    【讨论】:

    • input:16: 尝试调用一个 nil 值(全局 'unpack')
    • @user1768615 - 已更新。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-25
    • 1970-01-01
    • 2016-04-29
    • 1970-01-01
    • 2014-01-06
    • 1970-01-01
    • 2011-12-11
    相关资源
    最近更新 更多