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:
You could use a generic for loop to loop through these:
1 | for k, v in pairs (Items) do |
2 | print ( "Key: " .. k .. " Value: " .. v) |
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.
1 | for i, v in ipairs (Items) do |
2 | print ( "Index: " .. i .. " Value: " .. v) |
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.