← Back to Lua Course | Chapter 2: Variables & Types | Lesson 2 of 7

Local and global variables

Variables are global by default, so mark them local to keep them private to their block.

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

lua
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
Common Mistakes
  1. Forgetting local and accidentally creating a global
  2. Expecting a local to be visible after its block ends
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.