Generic For


The final loop that we will look is a Lua' implementation of the "collection-controlled" loop, the Generic For loop. The Generic For executes its loop body one time for each value generated by an "iterator function", which is a function that (generally) take a collection such as a list-like table as input, and returns an iterator over the values in the collection.

Lua provides two built-in iterator functions, pairs and ipairs. Let's take a look at them:

pairs

The general pattern for constructing a generic for loops using pairs is:

for [key], [value] in pairs([table]) do
    -- loop body
    -- repeat for each specified iteration
end

We provide examples and more information about using pairs in our section about iterating lists.

ipairs

Lua's second built-in iterator function is ipairs, which is similar to pairs except it returns an "index" with each value of returned. This will become more clear in a moment.

The general pattern for constructing a generic for loop using ipairs is:

for [idx], [value] in ipairs([table]) do
    -- loop body
    -- repeat for each specified iteration
end

where idx is an "index", or "loop-counter", that starts at 1 and increases by 1 for each iteration of the loop, and value is a value from the collection. Let's look at an example of how this works:

We provide examples and more information about using ipairs in our section about iterating lists.

Early Termination

Just like the [numeric for] loop, generic for loops can terminate early, using break or, when inside a function, return.