Local and global variables
Variables are global by default, so mark them local to keep them private to their block.
In this page:
Local and global variables
A variable assigned without the local keyword is global and lives in the table _G. A local variable is visible only inside the block where it is declared, and is faster to access. Reading a global that was never assigned gives nil rather than an error.
Note:
Almost always declare variables with local, and reserve globals for things you truly share.
Example: Local and global variables
g = "global"
local l = "local"
print(_G.g, _G.l)
do
local inner = "inside"
print(inner)
end
print(inner)
local x = 1
do
local x = 2
print(x)
end
print(x)
-- Output:
-- global nil
-- inside
-- nil
-- 2
-- 1
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting local and accidentally creating a global
- Expecting a local to be visible after its block ends
- Misspelling a variable and silently reading nil
Chapter Summary
- Undeclared assignment creates a global
- local limits scope to the block
- Globals live in _G
- Unknown globals are nil
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: