🎓 A1Learner
🔍
0 of 49 lessons completed

Lua Custom Environments

A custom environment is a table given to a chunk as its _ENV. The chunk then reads its free variables from that table instead of the global table.

load turns a string into a function

The returned value has function type. Calling it runs the code and gives 42.

local f = load('return 21 * 2', 'chunk', 't', {})
print(type(f))
print(f())

A chunk reads values from its own table

The value 20 comes from the table, not from a global. Adding 5 gives 25.

local env = {print = print, bonus = 20}
local f = load('print(bonus + 5)', 'chunk', 't', env)
f()

A global outside the table stays hidden

The global exists, but the chunk cannot see it. Its print shows nil.

secret = "top"
local env = {print = print}
local f = load('print(secret)', 'chunk', 't', env)
f()

Example

local env = {print = print, price = 100, discount = 10}
local f = load('print(price)\nprint(price - discount)', 'chunk', 't', env)
f()

Key points

  • load: a function that turns a string of code into a function that can be called.
  • Argument order: chunk, name, mode, then environment table.
  • Mode: the string t allows text chunks only.
  • Isolation: a custom environment hides globals that are not in its table.
  • Missing name: a free variable absent from the table reads as nil.

In this example, the env table holds print, price, and discount. The chunk first prints price, then prints price minus discount, so the two lines are 100 and 90.

Note

a chunk that needs print must receive print in its environment table.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

A chunk is loaded with env {score = 7} and its code is return score. What value does calling the chunk give?