Blocks

A Lua program has a block structure. Since blocks can contain subblocks, they form a tree-like structure, with the root being the whole program. The kinds of block are

  • the whole program (not necessarily in one file)
  • do ... end
  • functions, i.e. \ ... end
  • while ... end
  • repeat ... until <cond>
  • for ... end
  • if ... end
  • code in separate files
You can always wrap up statements in a do ... end block. A declaration of local variables has scope the block in which it occurs and in all subsequent subblocks of it. A variable which occurs in an expression that has been declared local in a surrounding block is called an upvalue of the block in which it occurs. A variable which is neither local nor an upvalue is sometimes referred to as a global variable, but this usage can be misleading. It is in fact a key in the current block's _ENV (environment) table. When a program starts the variable _G is set to this. It contains as keys all the built-in reserved names. You might like to try the following: open a taskwindow (CTRL-F12) and enter the command lua at the * prompt.

Then at Lua's > prompt enter

    for x, _ in pairs (_G) do print (x) end 
to see what is in the initial environment.

Note that a function's formal parameters, and a for-statement's iteration variables, are local variables, having local scope.

   for i = 1, 100 do print f (i) end
   print (i)           -->  nil     (i is out of scope)
You can set _ENV to whatever you like.

    local A = "Arthur"
    B = "Bob"
    do
      local _ENV = { print = print }
      print (A)  ---> Arthur
      print (B)  ---> nil
    end
So Arthur gets printed because A is an upvalue of the do ... end block, but B is not, nor is it in the current environment. Note the trope print = print . The left hand print is a key, making print in scope in the do ... end block, whereas the right hand print is a built-in value that would otherwise be out of scope there.

It is very important for the learner of Lua to recognize in a program

  • what are its blocks?
  • what are a block's local variables?
  • what are a block's upvalues?
  • what variable-names are in scope at a given place in the program?
You can use the _ENV variable to control the scope of variable-names.

Code in a separate file is treated like the body of a function of no arguments. So

   x = dofile (filename) 
is equivalent to

   local f = loadfile (filename); x = f ( ) 
If the code is required more than once, use loadfile to get it in a function f and call f many times rather than use dofile many times.