Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
2

What is a Generic for loop and an Iterator?

Asked by 8 years ago

The wiki page for a Generic for loop gives a vague description of a Generic for loop, and I want to know when you will need them, how they are used, and what iterators are and how to use them.

1 answer

Log in to vote
1
Answered by 8 years ago
Edited 8 years ago

The contents of the wiki page are quite advanced, going more into detail about iterator functions.

Generic for loops are intended for looping through a set of values, usually a table. To use a for loop, you need to provide it an iterator function. Conveniently, there are two iterator functions which are built in: pairs and ipairs. pairs will return key-value pairs, while ipairs will return index-value pairs. If you had the following table:

local Items = {
    Value1 = 5,
    Value2 = 3,
    Value3 = 1
}

You could use a generic for loop to loop through these:

for k, v in pairs(Items) do
    print("Key: " .. k .. " Value: " .. v)
end

This would print the following:

Key: Value1 Value: 5
Key: Value2 Value: 3
Key: Value3 Value: 1

You could also use ipairs, which will return an index rather than a key.

for i, v in ipairs(Items) do
    print("Index: " .. i .. " Value: " .. v)
end

This would print:

Index: 1 Value: 5
Index: 2 Value: 3
Index: 3 Value: 1

In most cases, you will be able to use pairs or ipairs rather than writing your own iterator.

Ad

Answer this question