Stateful Iterators with Closures
Build iterators that maintain state between calls using closures.
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) endAll lessons in this course
- The Generic for Protocol
- Stateless Iterators
- Stateful Iterators with Closures
- Coroutine-Based Generators