Lua: Variable Scope and Local Variables
In this lesson we will learn about variable scope and local variables. Variable scope pretty much just means where a variable lives, and declaring a local variable means it only exists in the local area (for example an if statement).
Alright, so basically this is a pretty easy subject, I feel the following piece of code demonstrates it well:
Variable = 1 --Set the global Variable to 1 if true then local Variable = 2 --Set a local varable to 2 print(Variable) --Print the local variable end print(Variable) --Print the global variable
Basically all variables in lua are global (available everywhere) unless specified otherwise (for example the "local" keyword in front of the variable name). Since in the above example we have set a global variable to 1, the output statements which don't have a local variable with the same name simply output this.
However in the if statement we have declared a "local" variable which only exists inside of the if statement, and in this case the if statement prints the local variable as its closer to its scope.
This whole local variable stuff also applies inside functions:
Variable = 1 --Set the global Variable to 1 function ScopeTest() local Variable = 2 --Set a local varable to 2 print(Variable) --Print the local variable end ScopeTest() print(Variable) --Print the global variable
And even with function directly:
function ScopeTest()
print("Global")
end
ScopeTest()
if true then
local function ScopeTest()
print("Local");
end
ScopeTest()
end
Local variables can often make code easier to test and debug, as well as sometimes fixing important issues.
Back to Lua

