🎓 A1Learner
🔍
0 of 52 lessons completed

Lua Stateful Iterators

A stateful iterator is a function that keeps its own control variable and returns the next value on each call. It returns nil when the sequence ends.

A closure iterator returns one value at a time

The factory returns an iterator over numbers up to a limit. A call past the limit returns nil.

local function up_to(limit)
  local i = 0
  return function()
    i = i + 1
    if i <= limit then
      return i
    end
    return nil
  end
end
local it = up_to(3)
print(it())
print(it())
print(it())
print(it())

A for loop drives the iterator to nil

The for loop calls the iterator on its own. It stops when the iterator returns nil.

local function up_to(limit)
  local i = 0
  return function()
    i = i + 1
    if i <= limit then
      return i
    end
    return nil
  end
end
for v in up_to(3) do
  print(v)
end

Two iterators move on their own

Each factory call makes a separate control variable. Calls to one iterator do not move the other.

local function up_to(limit)
  local i = 0
  return function()
    i = i + 1
    if i <= limit then
      return i
    end
    return nil
  end
end
local a = up_to(3)
local b = up_to(2)
print(a())
print(b())
print(a())
print(b())
print(a())
print(b())

Example

local function range_step(first, last, step)
  local current = first - step
  return function()
    current = current + step
    if current <= last then
      return current
    end
    return nil
  end
end
local a = range_step(2, 8, 3)
local b = range_step(10, 16, 3)
print(a())
print(b())
print(a())
print(b())
print(a())
print(b())
print(a())

Key points

  • Control variable: the local variable that tracks where the iterator is in the sequence.
  • Stateful iterator: a function that keeps its control variable between calls.
  • Nil ending: returning nil tells the for loop that the sequence is finished.
  • For loop use: a for loop calls the iterator again and again until it returns nil.
  • Independent iterators: each call to a factory makes an iterator with its own control variable.

In this example, the factory builds a stepping iterator from a first value, a last value, and a step. Iterator a steps by 3 from 2 to 8, and iterator b steps by 3 from 10 to 16. The interleaved prints show each iterator moving on its own, and the final call to a returns nil because a has passed its last value.

Note

a stateful iterator needs no state value from the for loop because the function itself holds the position.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

You make it = up_to(2) and call it three times. What do the three calls return, in order?