Lua Variable Scope
Scope is the part of a program where a name can be used. A local variable lives only inside its scope, from its own line to the end of its block.
A block has its own x
The do block creates a second, separate x. The prints show 99 inside the block and the untouched 10 after it.
local x = 10
do
local x = 99
print(x)
end
print(x)A function local stays inside
secret exists only inside setup, where it prints 42. After the call, the same name reads as a global that was never assigned, so it prints nil.
local function setup()
local secret = 42
print(secret)
end
setup()
print(secret)A loop variable ends with the loop
i belongs to the for loop and prints 1, 2, and 3 inside it. After the loop, the name i prints nil.
for i = 1, 3 do
print(i)
end
print(i)Example
local word = "outer"
print(word)
do
local word = "middle"
print(word)
do
local word = "inner"
print(word)
end
print(word)
end
print(word)Key points
- Block: a function body, a loop body, and a do ... end section are each a block.
- Lifetime: a local can be used from the line where it is written until the end of its block.
- Shadowing: an inner local with the same name hides the outer one inside its block only.
- Outside: after the block ends, the outer variable is visible again.
- Globals: a name assigned without local can be read anywhere in the program.
In this example, three different locals all share the name word, one at each level. Each print sees the nearest level, and closing a block brings the level outside it back into view.
Note
reading a global that was never assigned gives nil, not an error.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
An outer local x holds 5. A do block creates its own local x holding 8 and prints it, then the block ends and the program prints x again. What does the second print show?