🎓 A1Learner
🔍
0 of 49 lessons completed

Lua Environment Isolation

Environment isolation is the separation of two chunks so each keeps its own state. Each chunk runs under its own table, and a change in one table does not touch the other.

The same name holds different values

Each table supplies its own count. The two prints show 10 and 20.

local envA = {print = print, count = 10}
local envB = {print = print, count = 20}
local fA = load('print(count)', 'a', 't', envA)
local fB = load('print(count)', 'b', 't', envB)
fA()
fB()

A change in one table stays there

The first chunk adds 5, but the second chunk still sees 10. Nothing leaks across.

local envA = {print = print, total = 10}
local envB = {print = print, total = 10}
local fA = load('total = total + 5\nprint(total)', 'a', 't', envA)
local fB = load('print(total)', 'b', 't', envB)
fA()
fB()

A value written by one chunk is invisible to the other

The first chunk sets a value, but the second chunk reads nil for the same name.

local envA = {print = print}
local envB = {print = print}
local fA = load('value = 1\nprint(value)', 'a', 't', envA)
fA()
local fB = load('print(value)', 'b', 't', envB)
fB()

Example

local function makeEnv()
  return {print = print, count = 0}
end
local envA = makeEnv()
local envB = makeEnv()
local chunk = 'count = count + 1\nprint(count)'
local fA = load(chunk, 'a', 't', envA)
local fB = load(chunk, 'b', 't', envB)
fA()
fA()
fB()

Key points

  • Separate tables: two chunks with different environment tables have different state.
  • Same name: the same free variable name can hold different values in each table.
  • Assignment: assigning to a free variable writes into that chunk's own table.
  • No leak: a value written by one chunk never appears in the other chunk's table.
  • Independent runs: running one chunk again does not reset the other chunk's table.

In this example, makeEnv returns a fresh table on each call, so the two chunks get different tables. The same chunk string is loaded once per table, the first chunk runs twice and prints 1 then 2, and the second chunk runs once and prints 1.

Note

two chunks can still share a table if the same table is passed to both.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Two chunks run under different tables, each with count 0. One chunk adds 1 twice and the other adds 1 once. What is the count printed by the second chunk?