When a CPU runs a script, it executes that code from top to bottom and then exits the program after reaching the bottom.
But what if we didn’t want the script to exit? What if we wanted it to run continuously?
In contrast to this default behavior, the ‘while‘ loop returns to its beginning after reaching the bottom, forming a cyclic loop for as long as some condition is true.
local counter = 10
while counter > 0 do
print(counter)
counter = counter - 1
end
--Output: 10
--Output: 9
--Output: 8
--Output: 7
--Output: 6
--Output: 5
--Output: 4
--Output: 3
--Output: 2
--Output: 1
The condition is checked first and if true, enters the loop. At the top, the current counter value is printed out. Then one is subtracted from counter and the remaining value is reassigned to itself. After the counter reaches zero, the loop exits.
If you replace counter with just true, the loop will run indefinitely.
Regarding a running or indefinite loop, it is possible to exit a loop at anytime using the ‘break‘ statement.
local counter = 10
while true do
print(counter)
counter = counter - 1
if counter <= 0 then
break
end
end
This and the previous example have similar behavior.
Now lets use a loop to create a script that changes the color of the part a regular intervals.
local part = game.Workspace.Part
local counter = 15
while counter > 0 do
part.BrickColor = BrickColor.Random()
counter = counter - 1
end
This loop goes around 15 times and applies a random color to a part each time around the loop.
But something is strange. This script seems to change the color of the part just once.
What’s going on?
A computer program will generally try to run as fast as it possibly can. For an empty while loop, a dozen times through the loop might only take a handful of microseconds. Even changing the color of a part does not take much more time.
Meaning that those changes are happening too fast for us to perceive any changes (in addition to a framerate limit that is too slow).
We need a way to slow down the loop. We need a way to pause the loop for a set amount of time before changing the color again.