for loop

Lua has two flavors of the for loop, the numeric for and a generic for. The generic for is used to iterate over collections and will be covered in Chapter 3, Tables and Objects. For now, let's focus on the numeric for loop.

Syntactically, a numeric for loop consists of the for keyword, three expressions, and a do/end chunk. The three expressions are the initial expression, final expression, and step expression. Each expression is separated by a comma. The format for the loop looks like this:

for variable = initial_exp, final_exp, step_exp do
-- Chunk
end

The result of the intial expression should be numeric; it will be assigned to a variable local to the for loop. The loop will increment or decrement this variable so long as it is not equal to the final expression. The variable is incremented or decremented by the value of the step expression.

For example, the following code loops from 0 to 10. The loop increments the counter by one on each iteration and prints out the value of the counter:

for i = 0, 10, 1 do
print ( i )
end

You don't have to increment the loop by one every iteration. The step expression can be any number you wish. If we set the step expression to two, it will increment by 2 on each iteration:

for i = 0, 10, 2 do
print ( i )
end

A numeric for loop does not have to count up; it can count down. To count down, set the initial expression to be greater than the final expression and the step expression to be negative. Like counting up, the step expression can be any number:

for i = 10, 0, -1 do
print ( i )
end

Counting up by one is a very common use case for loops, so common that Lua provides a nifty shorthand for it with the for loop. If you provide only an initial expression and final expression, Lua will assume you want to count up by one and that the step expression is one:

for i = 0, 10 do
print ( i )
end
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.79.65