How to use a while statement in Lua

In Lua, the while keyword is used to repeat a piece of code given a certain condition.

The syntax is as follows.

while(condition)
do
   -- code
end

The illustration below demonstrates how the while keyword works.

Visual representation of a while statement.

Code

The code below uses the while statement to print the numbers from 11 to 1010.

i = 1
while(i <= 10)
do
print("number ", i)
i = i + 1
end

Expected output

number 	1
number 	2
number 	3
number 	4
number 	5
number 	6
number 	7
number 	8
number 	9
number 10

Explanation

The while statement in line 22 causes the lines after it to be executed repeatedly until the value of i becomes greater than 1010. Consequently, all the values of i in the range 00 to 1010 are printed.

Free Resources