Shared Upvalues Between Closures
Multiple closures sharing the same upvalue and mutation implications.
Sharing the Same Upvalue
Two closures defined in the same scope can share the exact same upvalue cell. Mutations by one are seen by the other.
local function makeGetterSetter()
local value = 0
local function get() return value end
local function set(v) value = v end
return get, set
end
local get, set = makeGetterSetter()
set(42)
print(get()) -- 42Why Sharing Happens
Lua does not copy upvalues per closure. All closures created in the same block pointing to the same local variable share one upvalue cell.
All lessons in this course
- What Are Upvalues?
- Shared Upvalues Between Closures
- Factory Functions and Generators
- Memoization with Closures