Local function declaration methods
There are 3 methods to define a local function
1.
local function reset()
--# code
end
2.
local reset = function()
--# code
end
3.
local reset
reset = function()
--# code
end
When looking at the above 3, you may think that #2 and #3 are no different, but they are, in fact very different! Believe it or not #1 and #3 are actually the same, #1 is just syntactical sugar for #3. In a normal situation you wouldn't find a need or difference between the 3, but there is when you're wanting to make a function that uses some recursion.
Effects on recursive local functions
In #2 recursion would not be possible. In example 1 and 3, the variable the function is stored in is created before the function is stored in it, this allows the function to be able to recursively call itself as there is already the function defined in the local space, whereas with #2 the variable is not yet defined in the local space when the function is compiled, meaning that when the function runs it cannot see itself in the local space and thus tries to reference 'reset' in the global space (which could make for some bad/unexpected bugs if there is a function called reset, or an error if there isn't). These effects are even greatly different when cyclic-recursion comes into play.
Effects on cyclic-recursive local functions
When dealing with cyclic-recursion you can only define them with the third method, take this example
local function w()
print("world")
h()
end
local function h()
write("hello ")
w()
end
h()
when the function
w is compiled, there is no variable
h in the local scope, so when attempting to call it, it will error out (if there is not variable
h in the global scope) as such when dealing with cyclic-recursion we must use forward declarations of our functions
local w, h --# forward local declaration of w and h
function w() --# or w = function()
print("world")
h()
end
function h()
write("hello ")
w()
end
h()
the above code will now work correctly due to the fact that both
w and
h are now defined in the local space. note that you no longer need to put local on the function declarations due to the fact that the name is already in the local space.
Final Note
Obviously the above problems do not apply to non-localised functions as they're in the global space. Both methods of declaring a global function are identical and do not have an effect on how they function, it is merely syntactical sugar and personal preference as to which declaration method you use (excluding when declaring in a table).
Good reference;
PIL: Non-Global Functions