8. Closures & Upvalues
Capturing variables across scope boundaries
A function that references a variable from an enclosing scope is called a closure. Closures are one of the most powerful features in programming languages — and one of the trickiest to implement correctly, especially in a bytecode VM.
The tricky part isn't what closures do (that's intuitive). It's what happens when the enclosing scope exits but the closure is still alive. Where do those captured variables live?
What is a closure?
A closure is a function paired with an environment. Here's the simplest example:
fn makeGreeter(greeting) {
fn greet(name) {
print greeting + ", " + name + "!";
}
return greet;
}
let hello = makeGreeter("Hello");
hello("world"); // "Hello, world!"
When makeGreeter returns, its local variable greeting would normally vanish —
its scope is over. But greet still needs it. The function greet closes over
the variable greeting, forming a closure.
The tree-walking approach: just keep the environment
In a tree-walking interpreter, closures are almost free. When you define a function, you store a reference to the current environment alongside the function body:
case 'FnDecl': {
const func = {
type: 'function',
params: node.params,
body: node.body,
closure: env, // <-- capture the environment
};
env.define(node.name, func);
break;
}
When you call the function, you chain a new environment off the closure environment (not the caller's environment):
case 'CallExpr': {
const callee = evaluate(node.callee, env);
const args = node.args.map(a => evaluate(a, env));
// New environment chains to the closure, not the caller
const callEnv = new Environment(callee.closure);
for (let i = 0; i < callee.params.length; i++) {
callEnv.define(callee.params[i], args[i]);
}
return executeBlock(callee.body, callEnv);
}
That's it. Because JavaScript (our host language) has garbage collection, the environment object stays alive as long as the closure references it. The captured variables just work.
But this approach keeps entire environment chains alive even if the closure only uses one variable. And in a bytecode VM, where locals live on a stack that gets popped when a function returns, this approach doesn't work at all.
The problem with stack-allocated locals
In a bytecode VM, local variables live on the value stack. When a function returns, its stack slots are reclaimed:
Stack during makeGreeter:
[ ... | greeting: "Hello" | greet: <fn> ]
^-- this slot disappears on return
After makeGreeter returns:
[ ... | hello: <fn> ]
greeting is gone!
If hello (which is greet) tries to access greeting later, the stack slot
no longer exists. We need a different strategy.
Upvalues: the Lua approach
The elegant solution, pioneered by Lua, is the upvalue. An upvalue is a small object that acts as an intermediary between the closure and the captured variable.
While the variable is still on the stack (its scope hasn't exited), the upvalue points directly into the stack slot. When the scope exits, the upvalue closes — it copies the value from the stack into its own storage.
class Upvalue {
constructor(stackIndex) {
this.stackIndex = stackIndex; // points into the VM stack
this.closed = false;
this.value = undefined; // used after closing
}
read(stack) {
if (this.closed) return this.value;
return stack[this.stackIndex];
}
write(stack, val) {
if (this.closed) { this.value = val; return; }
stack[this.stackIndex] = val;
}
close(stack) {
this.value = stack[this.stackIndex];
this.closed = true;
}
}
Open vs. closed upvalues
An open upvalue points to a stack slot that's still alive. A closed upvalue has hoisted the value off the stack.
This two-phase approach is what makes upvalues efficient: while the variable is on the stack, access is just as fast as any local variable (an array index). The overhead of an extra indirection only kicks in after the scope closes — which is exactly when you need it.
Compiling closures
The compiler needs to track which variables are captured. When it compiles an inner function, it checks each variable reference: is this a local in the current function, or does it belong to an enclosing function?
resolveVariable(name) {
// Check current function's locals first
const local = this.resolveLocal(name);
if (local !== null) return { type: 'local', slot: local };
// Check enclosing functions for upvalues
const upvalue = this.resolveUpvalue(name);
if (upvalue !== null) return { type: 'upvalue', index: upvalue };
// Must be a global
return { type: 'global', name };
}
resolveUpvalue(name) {
if (!this.enclosing) return null; // no enclosing function
// Is it a local in the immediately enclosing function?
const local = this.enclosing.resolveLocal(name);
if (local !== null) {
this.enclosing.markCaptured(local); // mark it as captured
return this.addUpvalue(local, true); // true = captures a local
}
// Is it an upvalue in the enclosing function? (transitive capture)
const upvalue = this.enclosing.resolveUpvalue(name);
if (upvalue !== null) {
return this.addUpvalue(upvalue, false); // false = captures an upvalue
}
return null;
}
The resolveUpvalue function is recursive — if a variable is two levels out,
the middle function also gets an upvalue that captures the outer function's
upvalue. Each function in the chain has its own upvalue index for the same
underlying variable.
VM instructions for upvalues
The bytecode VM needs three new instructions:
OP_CLOSURE— wraps a function with its upvalue referencesOP_GET_UPVALUE index— reads a captured variable through its upvalueOP_CLOSE_UPVALUE— closes an upvalue when its scope exits
case OP_CLOSURE: {
const fnIdx = this.chunk.code[this.ip++];
const func = this.chunk.constants[fnIdx];
const upvalueCount = this.chunk.code[this.ip++];
const upvalues = [];
for (let i = 0; i < upvalueCount; i++) {
const isLocal = this.chunk.code[this.ip++];
const index = this.chunk.code[this.ip++];
if (isLocal) {
// Capture a local from the current frame
upvalues.push(this.captureUpvalue(this.frame.fp + index));
} else {
// Capture an upvalue from the enclosing closure
upvalues.push(this.frame.closure.upvalues[index]);
}
}
this.stack.push({ type: 'closure', func, upvalues });
break;
}
case OP_GET_UPVALUE: {
const idx = this.chunk.code[this.ip++];
const upvalue = this.frame.closure.upvalues[idx];
this.stack.push(upvalue.read(this.stack));
break;
}
case OP_CLOSE_UPVALUE: {
this.closeUpvalues(this.stack.length - 1);
this.stack.pop();
break;
}
Sharing upvalues
What happens when two closures capture the same variable? They should share it. If one closure modifies the variable, the other should see the change:
fn make() {
let count = 0;
fn increment() { count = count + 1; }
fn getCount() { return count; }
return [increment, getCount];
}
let fns = make();
fns[0](); // increment
print fns[1](); // 1 — getCount sees the update
The VM ensures sharing by keeping a list of open upvalues. Before creating a new upvalue for a stack slot, it checks if one already exists:
captureUpvalue(stackIndex) {
// Reuse an existing upvalue for this slot
for (const uv of this.openUpvalues) {
if (uv.stackIndex === stackIndex) return uv;
}
// Create a new one
const upvalue = new Upvalue(stackIndex);
this.openUpvalues.push(upvalue);
return upvalue;
}
Both increment and getCount get the same upvalue object for count, so
mutations through one are visible to the other.
Closing over the variable, not the value
A common source of confusion: closures capture the variable, not its value at the time of capture. This matters most with loops:
let funcs = [];
let i = 0;
while (i < 3) {
funcs.push(fn() { return i; });
i = i + 1;
}
print funcs[0](); // 3 — not 0!
print funcs[1](); // 3 — not 1!
print funcs[2](); // 3 — not 2!
All three closures capture the same variable i. By the time they're called,
i has been incremented to 3. Every closure sees 3.
This is the classic loop closure bug, and it bites programmers in every language that has closures. The fix is to create a new variable in each iteration:
let funcs = [];
let i = 0;
while (i < 3) {
let j = i; // new variable each iteration
funcs.push(fn() { return j; });
i = i + 1;
}
print funcs[0](); // 0
print funcs[1](); // 1
print funcs[2](); // 2
Each iteration creates a new j in a new scope, so each closure captures a
different upvalue.
Closing upvalues at scope exit
When a scope exits, the VM must close every upvalue that points into the about-to-be-reclaimed
stack slots. The compiler emits OP_CLOSE_UPVALUE for each captured local:
closeUpvalues(lastSlot) {
for (let i = this.openUpvalues.length - 1; i >= 0; i--) {
const uv = this.openUpvalues[i];
if (uv.stackIndex >= lastSlot) {
uv.close(this.stack);
this.openUpvalues.splice(i, 1);
}
}
}
After closing, the upvalue holds the value directly. The stack slot can be safely popped.
The full picture
Closures in a tree-walking interpreter are simple: capture the environment object, and garbage collection keeps it alive. Closures in a bytecode VM are more work:
- The compiler detects captured variables and emits upvalue metadata.
OP_CLOSUREcreates upvalue objects, reusing existing ones for shared variables.OP_GET_UPVALUE/OP_SET_UPVALUEaccess variables through upvalues.OP_CLOSE_UPVALUEhoists values off the stack when their scope exits.
This Lua-style upvalue system is elegant because it adds zero overhead to variables that aren't captured. Only the variables that actually need to outlive their scope pay the cost of an upvalue wrapper.
Try It Yourself — Closure Visualizer
Type a program with closures. Watch upvalues get created when functions capture variables, see them transition from open (pointing at the stack) to closed (holding the value directly), and trace how shared upvalues connect multiple closures to the same variable.