Lesson 23 of 55
9 mins readPython Closures & Upvalues (Private State)
In Plain English
A closure is a function together with its lexical environment. In Lua, enclosed variables are called **upvalues**, retaining private state between invocations.
Deep Dive: How It Works
Upvalue: A local variable from an outer scope accessed by an inner closure.
Private Encapsulation: Factory functions can return closures that share private local state without globals.
Garbage Collection: Upvalues live as long as the referencing closure is reachable in memory.
Core Rules to Remember

Upvalues for Private State: Provides true object-like data privacy without classes.

Factory Function Pattern: Returns configured closures with private isolated state.
Live Interactive Example
Hit Run Code to see it liveCreating State Counters with Closures
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Output Console
Click "Run Code" to view the rendered output.
How it works: Each closure instance maintains its own private upvalue count.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Build Multiplier Closure Factory
Define `local function make_multiplier(factor) return function(n) return n * factor end end`.
Create `local triple = make_multiplier(3)` and print `"Triple 7: " .. triple(7)`.
1
2
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.