Related Tags

lua
communitycreator

# How to use a while statement in Lua

Dario Vincenzo Tarantini

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 $1$ to $10$.

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 $2$ causes the lines after it to be executed repeatedly until the value of i becomes greater than $10$. Consequently, all the values of i in the range $0$ to $10$ are printed.

RELATED TAGS

lua
communitycreator

CONTRIBUTOR

Dario Vincenzo Tarantini
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time