🎓 A1Learner
🔍
0 of 49 lessons completed

Lua Environment Lookup

An environment lookup is the way Lua finds a free variable. Lua reads a free variable from a table called _ENV.

A free variable reads from _ENV

The same value appears through the name and through _ENV. Both prints show the same number.

score = 40
print(score)
print(_ENV.score)

_ENV is a table

Its type shows what kind of value it is. The name lookup through it gives the stored word.

name = "Lua"
print(_ENV.name)
print(type(_ENV))

A local _ENV shadows the outer one

Inside the block, the local table supplies the names. Print is supplied in that table, so it still works inside the block.

do
  local _ENV = {print = print, greeting = "hi"}
  print(greeting)
end
print(greeting)

Example

level = "global"
local function show()
  local _ENV = {print = print, level = "local"}
  print(level)
end
show()
print(level)

Key points

  • Upvalue: _ENV is a value that every chunk carries with it.
  • Free variable: a name that is not a local in its own scope.
  • Lookup rule: Lua reads a free variable x as _ENV.x.
  • Global assignment: assigning to a name with no local stores it in _ENV.
  • Shadowing: a local named _ENV replaces the outer environment inside its scope.

In this example, level is first set as a global. The function show defines a local _ENV whose level is local, so its print shows local. After the call, the outer print reads the global again and shows global.

Note

a shadowed environment must supply print itself, or print reads as nil inside it.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Inside a block with local _ENV = {print = print, count = 9}, what does print(count) show?