|
|
A three expression loop is called a numeric for loop i=1 is the initial condition, 5 is the end condition, 1 is the step increment the third expression is optional, when omitted 1 is used as the step. |
for i=1, 5, 1 do print('first: ', i) end |
Note the variable declared in the loop is local to the body of the loop despite the lack of the local keyword. |
print('loop variable scope is local:', i) -- will print nil |
print() |
|
|
for i=1, 10, 1 do print('brk: ', i) if i == 5 then break end end |
print() |
|
A generic for loop supports traversing elements returned from an iterator
print all values of array |
arr = {'a', 'b', 'c', 'd'} for i,v in ipairs(arr) do print('arr: i, v', i, v) end |
print() |
|
Lua does not have a |
for i=1, 5 do if i % 2 == 0 then goto continue end print('odd: ', i) ::continue:: end |
$ lua for.lua first: 1 first: 2 first: 3 first: 4 first: 5 loop variable scope is local: nil |
|
brk: 1 brk: 2 brk: 3 brk: 4 brk: 5 |
|
arr: i, v 1 a arr: i, v 2 b arr: i, v 3 c arr: i, v 4 d |
|
odd: 1 odd: 3 odd: 5 |
Next example: While.