0Pricing
Lua Academy · Lesson

Stateless Iterators

Write stateless iterators like ipairs and implement custom variants.

What Is a Stateless Iterator?

A stateless iterator carries no internal state. All information is passed as arguments on each call: the invariant state and the current control variable.

ipairs: The Canonical Example

ipairs is stateless — it uses the table as state and the current index as the control variable.

local function myIpairs(t, i)
  i = i + 1
  local v = t[i]
  if v ~= nil then return i, v end
end
-- Use: for i,v in myIpairs, t, 0 do

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