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.
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.