Glossary

What is an upvalue?

An upvalue is a closure's handle on a variable that belongs to an enclosing function. The term comes from Lua, and Crafting Interpreters uses the same design in clox: upvalues are what let a function keep using a local variable after the function that declared it has returned.

Taught in Crafting Interpreters 25: Closures

Open and closed

In a stack-based VM, locals live on the stack and vanish when their function returns. A closure cannot hold a pointer into the stack forever. So an upvalue starts open, pointing at the variable's stack slot while the enclosing function is still running, and when that function returns the VM closes it: it copies the value into the upvalue object on the heap and points there instead.

Two closures that capture the same variable must share one upvalue, or they would each see a private copy. clox keeps a sorted list of open upvalues so it can find and reuse an existing one.

Where it is taught

Chapter 25, Closures, on the path in the clox weeks. It is often the hardest chapter in the book; draw the stack and the upvalues on paper for a small example before you write the code.

Questions

Does jlox use upvalues?

No. jlox closures hold a reference to their whole enclosing environment, a heap-allocated Java map, so the problem never arises.