A while loop will keep going round and round until it's condition is met. Conditions are explained in the "Conditional Statements" section of the main tutorial.
Here is an example of a while loop:
x = 1
while(x < 20) do
x = x * 2
echo("X: " .. x)
end
What this loop does is keep going while x
is less than twenty. So it will echo:
X: 2
X: 4
X: 8
X: 16
X: 32
So why does it echo when X 32
? Because it checks if x is less than twenty BEFORE it multiplies it. If we moved the x = x * 2
line under the echo("X: " .. x)
line we would get different results:
X: 1
X: 2
X: 4
X: 8
X: 16
We could also use a repeat until loop.
x = 1
repeat
x = x * 2
echo("X: " .. x)
until x >= 20
This is sort of the opposite of a while loop, as it will do the functions until the x is greater than or equal to 20. It will produce the same output as the first while loop.