Lua是否有可能停止"从表中执行任何代码?

时间:2017-07-13 18:43:16

标签: lua lua-table

让我对Lua感兴趣的事实是你可以在表中运行任何函数,无论它是否返回任何函数,我所说的是一个例子:

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

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

1 个答案:

答案 0 :(得分:4)

你不是以某种方式存储函数,而是存储调用结果。

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

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]()
相关问题