【问题标题】:Lua is it possible to "halt" any code execution from within a table?Lua是否可以从表中“停止”任何代码执行?
【发布时间】:2017-07-14 03:10:41
【问题描述】:

Lua 让我感兴趣的一点是,你可以在一个表中运行任何函数,不管它是否返回任何东西,我正在谈论的一个例子是:

local my_table = {
    print("output from a table!");
    warn("more output from a table!");
};

有趣的是,一旦创建了这个表,其中的两个函数都会运行,并且 my_table[1] 和 [2] 都等于 nil(因为 print 和 warn 不返回值)。但是,是否有任何方法可以在创建表时“停止”这两个函数的执行,甚至可能在以后“开始”运行它们,如果满足或不满足某个条件? 我将不胜感激任何帮助;谢谢

【问题讨论】:

    标签: lua lua-table


    【解决方案1】:

    您不是以这种方式将函数存储在表中,而是存储调用的结果。

    如果您需要函数,请显式创建匿名函数。

    local mytable = {
        function() print("output from a table!") end,
        function() warn("more output from a table!") end
    }
    

    如果您不喜欢这种方式,还有另一种方式。在词法闭包中捕获函数和参数,并在调用闭包时应用存储的参数。

    local function delay(func, ...)
        local args = {...}
        return function()
            func(table.unpack(args))
        end
    end
    
    local mytable = {
        delay(print, "output from a table!"),
        delay(warn, "more output from a table!")
    }
    
    mytable[1]()
    mytable[2]()
    

    【讨论】:

    • 这是个好主意!我会根据我的情况看看我能做些什么来让它正常工作,谢谢! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-15
    • 2020-11-05
    • 2011-11-01
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多