# While loop in Lua Programming

LuaServer Side ProgrammingProgramming

A while loop is an indefinite loop that can be modified to run for a finite number of iterations based on the condition we provide.

In Lua, the while condition is tested first. If the condition turns out to be false, then the loop ends, otherwise, Lua executes the body of the loop and repeats the process.

## Syntax

while( condition ){
// do this
}

## Example

Consider the example shown below −

a = {1,2,3,4,5}
local i = 1
while a[i] do
print(a[i])
i = i + 1
end

## Output

1
2
3
4
5

It should be noted that if we forget to remove the increment condition, then we will be in an infinite loop, as the condition inside the parentheses after the while keyword will always be true. Hence, it can cause our program to behave abnormally.

## Example

Consider the example shown below −

a = {1,2,3,4,5}
local i = 1
while a[i] do
print(a[i])
--i = i + 1
end

## Output

The output will contain 1 infinite number of times and the program might get stuck, so it is always recommended that you use the increment statement.

1
1
1
1
1
1
1
….
….
….
Published on 01-Dec-2021 10:53:47