Skip to main content

Scope

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.

Scope

When the above program runs:

  • Block 2 can access the local variable a.
  • Block 3 can access the local variables a, b and the function myFunction() that are declared in blocks 1 and 2.
  • Block 1 cannot access the local function myFunction() or the variables b, c that are declared in blocks 2 or 3.
  • Block 2 cannot access the local variable c that is declared in block 3.