TExcelTAD
Home › Lua › Lua Scope: local vs global

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.

lua · try it yourself
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: nil
HELLO
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:

lua · try it yourself
for i = 1, 2 do
  local square = i * i
  print(i, square)
end
print(i, square)   -- both gone
1	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:

lua · try it yourself
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:

lua · try it yourself
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:

lua · try it yourself
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:

lua
local insert, floor = table.insert, math.floor

Variables 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):

lua · try it yourself
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?

  1. Everywhere in the file
  2. Only inside that if block, after its declaration
  3. Only in the next block
  4. In all functions

Where are global variables stored?

  1. In the registry only
  2. In the table _G
  3. In package.loaded
  4. On the C stack

What happens when you forget local on a variable inside a function?

  1. Syntax error
  2. It becomes a global variable
  3. It becomes a constant
  4. It is local anyway