0Pricing
Lua Academy · Lesson

The Generic for Protocol

Understand the three-value iterator protocol: iterator function, state, control variable.

How Generic for Works

The for statement calls an iterator function each iteration. It passes a state and a control variable, and stops when the function returns nil.

Three-Value Return

for var in iter, state, init do — Lua unpacks this as: iterator function iter, invariant state state, initial control variable init.

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