The for loop
There are two types of for loops in Lua
- Numeric for loop - usually use integers as the loop variable
- Generic for loops - use iterators to traverse a data structure
The basic structure of the numeric for loop is the following
- Note that this returns oak and cherry as the results
- Because of the step of 2 in the loop variable
- Note that this returns oak and cherry as the results
--for var = exp1, exp2, exp3 do -- body of the loop that does something --end -- exp1 is used to initialize the loop variable -- which is local to the for loop block -- exp2 is used to test against the value of the loop variable -- exp3 tells how much to step the loop variable after each loop -- An example of a for loop local a = {"Oak", "Pine", "Cherry", "Fir"} for i = 1, 4, 2 do print(a[i]) end