Closures
A closure is a function that remembers the local variables from where it was created.
In this page:
Closures
When a function is defined inside another function it can use the outer function's local variables, called upvalues. These variables stay alive after the outer function returns, so each call to a factory creates an independent set. Closures are commonly used for counters, private state and callbacks.
Note:
Each call to the outer function creates fresh upvalues, so counters made separately do not interfere.
Example: Closures
local function counter()
local n = 0
return function()
n = n + 1
return n
end
end
local c1, c2 = counter(), counter()
print(c1(), c1(), c1())
print(c2())
local fns = {}
for i = 1, 3 do fns[i] = function() return i end end
print(fns[1](), fns[2](), fns[3]())
-- Output:
-- 1 2 3
-- 1
-- 1 2 3
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Expecting all closures to share one counter
- Capturing a loop variable and expecting one shared copy
- Assuming local variables die when the function returns even if captured
Chapter Summary
- Inner functions see outer locals
- Captured variables are upvalues
- Each factory call has its own state
- Useful for counters and private data
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: