Stateful Iterators with Closures
Build iterators that maintain state between calls using closures.
Stateful Iterators with Closures is a free Lua Academy lesson on CoddyKit. This is lesson 3 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Lua Academy learning path, and your progress syncs across the web and the CoddyKit app. The Lua Academy course includes 4 lessons in total.
When Closures Help
When an iterator needs to maintain complex, evolving state (position, stack, history), closures are the natural tool. The state lives in upvalues.
Closure Iterator Pattern
Return a single function; state is kept in upvalues. The generic for provides no external state — just calls the function each time.
local function chars(s)
local i = 0
return function()
i = i + 1
local c = s:sub(i, i)
return c ~= "" and c or nil
end
end
for c in chars("lua") do print(c) endFile Line Iterator
A classic stateful closure iterator yields lines from a file handle until EOF.
local function lines(filename)
local f = io.open(filename, "r")
return function()
local line = f:read("*l")
if not line then f:close() end
return line
end
endFiltering Iterator
Wrap an existing iterator with a closure that skips elements not matching a predicate.
local function filtered(iter, pred)
return function()
local v = iter()
while v ~= nil and not pred(v) do
v = iter()
end
return v
end
endMapped Iterator
A mapping iterator transforms each element on the fly without building an intermediate table.
local function mapped(iter, fn)
return function()
local v = iter()
if v ~= nil then return fn(v) end
end
endZipped Iterator
A zip iterator pulls from two iterators simultaneously, stopping when either is exhausted.
local function zipped(iter1, iter2)
return function()
local a, b = iter1(), iter2()
if a ~= nil and b ~= nil then return a, b end
end
endChained Iterator
A chain iterator exhausts one iterator before switching to the next.
local function chained(...)
local iters = {...}
local idx = 1
return function()
while idx <= #iters do
local v = iters[idx]()
if v ~= nil then return v end
idx = idx + 1
end
end
endCounted Iterator
Limit an iterator to at most N values using a closure counter.
local function take(n, iter)
local count = 0
return function()
count = count + 1
if count <= n then return iter() end
end
endTree Walk Iterator
A depth-first tree walk uses a stack (table as upvalue) to maintain traversal state.
local function dfs(root)
local stack = {root}
return function()
if #stack == 0 then return nil end
local node = table.remove(stack)
for _, child in ipairs(node.children or {}) do
stack[#stack+1] = child
end
return node
end
endMemory Considerations
Stateful iterators allocate a closure object. For extremely tight inner loops, a stateless iterator may be preferable. For complex traversals the closure is well worth it.
Comparison: Stateful vs Stateless
- Stateful: complex state, any traversal order, easy to write.
- Stateless: simple sequential access, zero allocation, fast.
Stateful Iterator Question
Where does a stateful closure iterator store its state?
Recap: Stateful Iterators
Closure-based stateful iterators store complex traversal state in upvalues, enabling filters, maps, trees, and lazy pipelines — all composable and memory-efficient.
Learn Lua with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 40
- Lessons
- 159
Frequently Asked Questions
Is the “Stateful Iterators with Closures” lesson free?
Yes — any 3 lessons of the Lua Academy learning path, including “Stateful Iterators with Closures”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Lua Academy course includes 4 lessons in total.
What will I learn in “Stateful Iterators with Closures”?
Build iterators that maintain state between calls using closures. You practise Lua Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Lua Academy?
No prior experience is required. Lua Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 4.
How long does the “Stateful Iterators with Closures” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Lua Academy lesson?
Yes. Every Lua Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- The Generic for Protocol
- Stateless Iterators
- Stateful Iterators with Closures
- Coroutine-Based Generators