# What is an upvalue?

> An upvalue is how a closure reaches a variable from an enclosing function. Open and closed upvalues explained, as built in clox chapter 25.

**Upvalue**: An upvalue is a reference from a closure to a local variable of an enclosing function, which stays valid after that function returns.

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.

## 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](https://cracked.guide/guide/ci-25), 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.

---

Source: https://cracked.guide/glossary/upvalue
cracked.guide: A free, dated 145-week path to getting genuinely cracked at programming.
