3.5 – Visibility Rules

Lua is a lexically scoped language. The scope of a local variable begins at the first statement after its declaration and lasts until the last non-void statement of the innermost block that includes the declaration. Consider the following example:

  1. x = 10 -- global variable
  2. do -- new block
  3. local x = x -- new 'x', with value 10
  4. print(x) --> 10
  5. x = x+1
  6. do -- another block
  7. local x = x+1 -- another 'x'
  8. print(x) --> 12
  9. end
  10. print(x) --> 11
  11. end
  12. print(x) --> 10 (the global one)

Notice that, in a declaration like local x = x, the new x being declared is not in scope yet, and so the second x refers to the outside variable.

Because of the lexical scoping rules, local variables can be freely accessed by functions defined inside their scope. A local variable used by an inner function is called an upvalue, or external local variable, inside the inner function.

Notice that each execution of a local statement defines new local variables. Consider the following example:

  1. a = {}
  2. local x = 20
  3. for i=1,10 do
  4. local y = 0
  5. a[i] = function () y=y+1; return x+y end
  6. end

The loop creates ten closures (that is, ten instances of the anonymous function). Each of these closures uses a different y variable, while all of them share the same x.