Lua Scope: local vs global
Scope is the region of code where a variable can be seen. Lua uses lexical scope: a local variable is visible from the line after its declaration to the end of the block that contains it.
local greeting = "hello" -- visible in the whole chunk
if true then
local shout = greeting:upper() -- visible only inside this if-block
print(shout)
end
print(greeting)
print(shout) -- outside the block: nilHELLO
hello
nil
Blocks create scopes
Every do … end, if, loop body and function body is a block with its own scope. A local declared inside it disappears when the block ends. Loop variables are local to the loop:
for i = 1, 2 do
local square = i * i
print(i, square)
end
print(i, square) -- both gone1 1
2 4
nil nil
Shadowing
An inner local with the same name hides (shadows) the outer one until the inner block ends. The outer variable is untouched:
local colour = "red"
do
local colour = "blue"
print("inside:", colour)
end
print("outside:", colour)inside: blue
outside: red
Shadowing is legal but can be confusing. Linters warn about it.
Globals live in a table: _G
Global variables are really fields of a table called _G (the global environment). Assigning score = 10 is the same as _G.score = 10:
score = 10
print(_G.score)
_G["level"] = 3
print(level)
print(type(_G.print), type(_G.string))10
3
function table
Even the standard functions (print, string, math) are just globals stored in _G.
The danger of accidental globals
Forgetting local inside a function creates a global that leaks out and can clash with other code:
local function countVowels(text)
count = 0 -- oops: no 'local'
for ch in text:gmatch("[aeiou]") do
count = count + 1
end
return count
end
print(countVowels("banana"))
print("leaked global:", count)3
leaked global: 3
If two functions both use a global count, they overwrite each other's value. Fix it by writing local count = 0.
Why prefer locals
local |
global | |
|---|---|---|
| Visibility | only its block | the whole program, every module |
| Speed | stored in a register: fast | a table lookup in _G: slower |
| Name clashes | impossible outside the block | easy |
| Garbage collection | freed when no longer reachable | lives until set to nil |
A common idiom in performance-sensitive code is to cache globals in locals at the top of a file:
local insert, floor = table.insert, math.floorVariables declared before use
A local is only visible after the statement that declares it. This matters for recursive local functions, which is why Lua has the local function syntax (it declares the name first):
local function factorial(n)
if n <= 1 then return 1 end
return n * factorial(n - 1) -- works: the name is already in scope
end
print(factorial(5))120
Test yourself
Where is a local declared inside an if block visible?
- Everywhere in the file
- Only inside that
ifblock, after its declaration - Only in the next block
- In all functions
Where are global variables stored?
- In the registry only
- In the table
_G - In
package.loaded - On the C stack
What happens when you forget local on a variable inside a function?
- Syntax error
- It becomes a global variable
- It becomes a constant
- It is local anyway