Generic for
Introduction
Basic for loops have already been covered in Loops. If you haven't already done so, please review Loops.
Discussion
The generic for loop traverses all values returned by the iterator. The iterator is the number that keeps track of how many times a for loop is supposed to run. This is different from a the numeric for loop in Loops in that before we were simply displaying the iterator (or a function of the iterator) itself:
Numeric for:
for i=20,1,-2 do print(i) end
Now what we are doing is assigning a value to the iterator.
Let's make Table with the months of the year:
months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}
We know that there are twelve months in the year, and we can also call January "month #1", February "month #2", and so on.:
revmonths = {["January"] = 1, ["February"] = 2, ["March"] = 3, ["April"] = 4, ["May"] = 5, ["June"] = 6, ["July"] = 7, ["August"] = 8, ["September"] = 9, ["October"] = 10, ["November"] = 11, ["December"] = 12}
Notice how we assigned a unique month number to each month of the year. Now we can find our iterators again:
print(revmonths["January"]) -- prints 1, which is the first month of the year print(revmonths["December"]) -- prints 12, which is the twelfth month of the year
Script
months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"} revmonths = {["January"] = 1, ["February"] = 2, ["March"] = 3, ["April"] = 4, ["May"] = 5, ["June"] = 6, ["July"] = 7, ["August"] = 8, ["September"] = 9, ["October"] = 10, ["November"] = 11, ["December"] = 12} print(revmonths["January"]) print(revmonths["February"]) print(revmonths["March"]) print(revmonths["April"]) print(revmonths["May"]) print(revmonths["June"]) print(revmonths["July"]) print(revmonths["August"]) print(revmonths["September"]) print(revmonths["October"]) print(revmonths["November"]) print(revmonths["December"])
Instead of having to slough through typing a print() command for every month, you can now do a for loop:
months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"} revmonths = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"} for i,v in ipairs(months) do revmonths[v] = i print(revmonths[v]) end