How are variables scoped?
By default, variables are global, and are only local if they are function arguments or explicitly declared as local
. (This is opposite to the Python rule, where you need a global
keyword.)
G = 'hello' -- global function test (x,y) -- x,y are local to test
local a = x .. G
local b = y .. G
print(a,b)
end
Local variables are 'lexically scoped', and you may declare any variables as local within nested blocks without affecting the enclosing scope.
do
local a = 1
do
local a = 2
print(a)
end
print(a)
end
=>
2
1
There is one more scope possibility. If a variable is not local, in general it is contained inside the module scope, which usually is the global table (_G
if you want it explicitly) but is redefined by the module
function:
-- mod.lua (on the Lua module path)
module 'mod'
G = 1 -- inside this module's context function fun(x) return x + G end --ditto
-- moduser.lua (anywhere)
require 'mod'
print(mod.G)
print(mod.fun(41))
1.18.1 Why aren't variables locally scoped by default?
It certainly feels easy to only explicitly declare globals when they are in a local context. The short answer is that Lua is not Python, but there are actually good reasons why lexically-scoped local variables have to be explicitly declared. See the wiki page.