Iterators utilize a form of the for
loop known as the generic for loop.
The generic form of the for
loop uses three parameters:
nil
signals termination.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