Forward Referencing Will Save You

When I first started using the Corona SDK and programming with Lua, one of the things that got to me was the structure of the Lua files, and the goal of keeping everything local.

I understood the benefits of using local variables and functions over globals, but putting everything into practice often felt like I was putting together a complex puzzle just trying to keep things local.

This was mainly because when you define a local variable or function, like so:

local myVariable = 100

You cannot access that variable in lines before it, as illustrated below:

print( myVariable )    --> output: nil

local myVariable = 100

print( myVariable )    --> output: 100

And that’s exactly what caused the “puzzle” effect as I like to call it. Because inevitably, some function, somewhere else in the module would need to access that variable but not be able to simply because of the location it was defined in the code (even if during execution, the variable was set at the proper time).

Then, I learned about a wonderful thing called forward referencing.

Forward referencing is simply defining a variable before you intend to use it, but it provides a frame of reference for other code/functions that need to use the variable. And as long as the forward reference is local, then it will remain local throughout your code (unless you define it as local again in a separate codeblock).

Now, this may seem very obvious, but what’s not always obvious to everyone (even to me when I first started out), is that in Lua, functions are also variables… which means you can forward reference functions as well.

This first example is the “puzzle effect” (that can really get out of hand when you have hundreds or thousands of lines of code):

local callBack = function()
    myFunction()  --> ERROR: myFunction() does not exist
end

local myFunction()
    print( "Hello World" )
end

callBack()  --> will produce error (see above)

And here is the same code above, but this time, with a forward reference:

local myFunction  --> forward reference

local callBack = function()
    myFunction()  --> output: "Hello World"
end

myFunction = function()  --> still local
    print( "Hello World" )
end

callBack()

And that’s where forward referencing really takes the cake. Notice how if you have a forward reference in your module, you simply define the function later on as you would a global, but magically, the function remains local (because of the forward reference).

So if you’re stuck in the “puzzle effect” or have just resorted to using globals to overcome this issue, then look no further, because forward referencing will save you (from going insane).

HostGator $3.96

$3.96 for web hosting – used by jonbeebe.net. Get started today.