How do I call a function that needs to be called from above its creation? I read something about forward declarations, but Google isn't being helpful in this case. What is the correct syntax for this?
To write a forward declaration for a function, we use a declaration statement called a function prototype. The function prototype consists of the function header (the function's return type, name, and parameter types), terminated with a semicolon. The function body is not included in the prototype.
++ is not a C function, it is an operator. So Lua being able to use C functions is not applicable.
However, because Lua has no variable hoisting, I can't reference a function that is defined later in the file.
Lua is a dynamic language and functions are just a kind of value that can be called with the ()
operator. So you don't really need to forward declare the function so much as make sure that the variable in scope when you call it is the variable you think it is.
This is not an issue at all for global variables containing functions, since the global environment is the default place to look to resolve a variable name. For local functions, however, you need to make sure the local variable is already in scope at the lexical point where you need to call the value it stores, and also make sure that at run time it is really holding a value that can be called.
For example, here is a pair of mutually recursive local functions:
local a,b a = function() return b() end b = function() return a() end
Of course, that is also an example of using tail calls to allow infinite recursion that does nothing, but the point here is the declarations. By declaring the variables with local
before either has a function stored in it, those names are known to be local variables in lexical scope of the rest of the example. Then the two functions are stored, each referring to the other variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With