lua

Lua: How to call a function prior to it being defined?


What is the syntax to create the function, but then add it's implementation further down in code?

So roughly like this:


Solution

  • oh...so there's really no way to call funcName prior to having actually defined the function then? i.e. you still need to make sure defineIt is called before your first call to funcName itself?

    I wanted to clarify this point, and I felt that an answer would be the better way than a comment.

    Lua is a much simpler language than C or C++. It is built on some simple foundations, with some syntactic sugar to make parts of it easier to swallow.

    There is no such thing as a "function definition" in Lua. Functions are first-class objects. They are values in Lua, just like the number 28 or the string literal "foo" are values. A "function definition" simply sets a value (namely, the function) into a variable. Variables can contain any kind of value, including a function value.

    All a "function call" is is taking the value from a variable and attempting to call it. If that value is a function, then the function gets called with the given parameters. If that value is not a function (or a table/userdata with a __call metamethod), then you get a runtime error.

    You can no more call a function that hasn't been set in a variable yet than you can do this:

    local number = nil
    local addition = number + 5
    number = 20
    

    And expect addition to have 25 in it. That's not going to happen. And thus, for the same reason, you can't do this:

    local func = nil
    func(50)
    func = function() ... end
    

    As Paul pointed out, you can call a function from within another function you define. But you cannot execute the function that calls it until you've filled in that variable with what it needs to contain.