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
Then at Lua's > prompt enter
for x, _ in pairs (_G) do print (x) endto 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 endSo 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
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.