The While Loop is a "condition-controlled" loop, which executes a block of code 0 or more times, stopping when the controlling condition is true.
While loops follow the pattern:
while [boolean expression] do
-- loop body
-- repeat as long as boolean expression is true
end
As a simple example, let's sum up all numbers from 0 to 4:
local x = 0
local result = 0
while x < 5 do
result = result + x
x = x + 1
end
print(result) -- 10
The break
statement can be used to terminate a while loop early. The following is equivalent to
the previous example.
local x = 0
local result = 0
while true do
result = result + x
x = x + 1
if x >= 5 then
break
end
end
print(result) -- 10
Note that in this case we used a boolean expression that is simply true. This is a common practice in many situations, but requires a bit of care in order to prevent infinite loops.
We should point out that when a While Loop is contained within a function, the loop can also
terminate when it encounters a return
statement:
local function sum()
local x = 0
local result = 0
while true do
result = result + x
x = x + 1
if x >= 5 then
return result
end
end
end
print(sum()) -- 10