Scope controls the accessibility of a variable or function. The scope of a variable or function is defined when the variable or function is declared. Each block of code establishes its own scope, and has access to the scope of its parents.
In Lua, there are two types of scope, “global” and “local”. Variables or functions declared in the global scope can be accessed from anywhere; whereas variables or functions declared in the local scope can only be accessed within the same block, or from any child blocks.
To declare a variable or function with local scope, include the
local keyword before the name of the variable or function. Any variable or function declared without the
local keyword will be in the global scope.
When the above program runs:
- Block 2 can access the local variable
- Block 3 can access the local variables
band the function
myFunction()that are declared in blocks 1 and 2.
- Block 1 cannot access the local function
myFunction()or the variables
cthat are declared in blocks 2 or 3.
- Block 2 cannot access the local variable
cthat is declared in block 3.