We’ve only defined functions in the outermost scope of the script. But earlier, I implied that functions can also be defined within the scope of statement or function because Lua has first class functions.
Not to be confused with invoking a function from within a function, we can define a function within another scope just like we normally would any function.
if true then
local myVar = "I am a local variable"
local function innerFunction(argument)
print(myVar)
print(argument)
return math.random(100)
end
local result = innerFunction("I am a function argument")
print("The result is:", result)
end
A subtlety is that nested functions also have access to any local variables of its encompassing scope.
We see here that myVar is available to the nested function without having to pass it as an argument.
If this function was defined, exactly as is but the outside of if statement, it would no longer have access to that local variable.
This is called Lexical Scope and probably what we would assume the behavior to be.
With that in mind and what we know about local variables on the stack, what would happen if we defined a nested function that requires the lexically scoped data from its enclosing function.
But the reference to that nested function is returned and is invoked after the enclosing function has exited?
local function getFunction()
local message = "I'm local to the 'if' statement"
local function innerFunction()
print(message)
end
return innerFunction
end
local someFn = getFunction()
print(message) --Output: nil
someFn() --Output: ???
The message is local to the enclosing function and the nested function accesses lexically.
After the enclosing function exits, it’s stack frame is returned and the local data, including the message, is lost.
But innerFunction/someFn needs that data. What happens if we invoke it now that the enclosing function has returned?
Don’t cheat. Think about your answer.