0
votes

Something that intrigues me about Lua is the fact that you can run any function from within a table, regardless of whether it returns anything or not, an example of what I am talking about is:

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

The funny thing is that as soon as this table is created both functions inside of it are ran, and both my_table[1] and [2] are equal to nil (because print and warn do not return a value). However is there any way to per-say "halt" both functions from executing whenever the table is created, and possibly even "start" running them later, if a certain condition is met or not? I would appreciate any help; Thanks

1

1 Answers

4
votes

You're not storing functions in a table that way, you're storing results of calls.

If you need functions, create anonymous functions explicitly.

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

If you don't like this way, there's another. Capture function and arguments in a lexical closure, and apply stored arguments when that closure will be called.

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]()