for loop in Lua

Advertisements


A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

Syntax:

The syntax of a for loop in Lua programming language is:

for init,max/min value, increment
do
   statement(s)
end

Here is the flow of control in a for loop:

  1. The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables.

  2. Next, the max/minThis is maximum or minumum value till which the loop continues to execute. It creates a condition check internally to compare between the intial value and maximum/minimum value.

  3. After the body of the for loop executes, the flow of control jumps back up to the increment/decrement statement. This statement allows you to update any loop control variables.

  4. The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the for loop terminates.

Flow Diagram:

for loop in Lua

Example:

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

When the above code is build and executed, it produces the following result:

10
9
8
7
6
5
4
3
2
1


Advertisements
Advertisements