0Pricing
Lua Academy · Lesson

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())  -- 42

Why 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

  1. What Are Upvalues?
  2. Shared Upvalues Between Closures
  3. Factory Functions and Generators
  4. Memoization with Closures
← Back to Lua Academy