Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forward define a function in Lua?

Tags:

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?

like image 535
Elliot Bonneville Avatar asked May 20 '11 04:05

Elliot Bonneville


People also ask

How do you forward a function declaration?

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.

Can you do ++ in Lua?

++ is not a C function, it is an operator. So Lua being able to use C functions is not applicable.

Does Lua have Hoisting?

However, because Lua has no variable hoisting, I can't reference a function that is defined later in the file.


1 Answers

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.

like image 173
RBerteig Avatar answered Sep 24 '22 05:09

RBerteig