Lua Generic For Loop


Example

Iterators utilize a form of the for loop known as the generic for loop.

The generic form of the for loop uses three parameters:

  1. An iterator function that gets called when the next value is needed. It receives both the invariant state and control variable as parameters. Returning nil signals termination.
  2. The invariant state is a value that doesn't change during the iteration. It is typically the subject of the iterator, such as a table, string, or userdata.
  3. The control variable represents an initial value for iteration.

We can write a for loop to iterate all key-value pairs in a table using the next function.

local t = {a=1, b=2, c=3, d=4, e=5}

-- next is the iterator function
-- t is the invariant state
-- nil is the control variable (calling next with a nil gets the first key)
for key, value in next, t, nil do
  -- key is the new value for the control variable
  print(key, value) 
  -- Lua calls: next(t, key)  
end