0Pricing
Lua Academy · Lesson

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) end

All lessons in this course

  1. The Generic for Protocol
  2. Stateless Iterators
  3. Stateful Iterators with Closures
  4. Coroutine-Based Generators
← Back to Lua Academy