What is a loop?
A loop
is a block of code that will run indefinitely unless told to stop.
What kind of loops are there?
There are 3 main types of loops. For
, While
, and Repeat
. Each of them work very differently.
For
A For loop is a loop that will loop a defined amount of times. There a quite a few different ways to do this, which is why I recommend looking at the wiki. For example:
2 | print ( "This is the for loop" ) |
While
A While loop is a loop that will run indefinitely, until told to stop. The ways to stop a while loop are either to make it a variable loop or break it. And you always need a wait()
function. Example:
02 | local changepart = game.Workspace.Part |
06 | if changepart.Changed then |
Repeat
A Repeat loop is a loop that will run until a condition is met. This is particularly useful when seeing if a LocalPlayer
is there. The following example must be in a LocalScript
.
1 | local players = game:GetService( "Players" ) |
3 | repeat wait() until players.LocalPlayer |
5 | local player = players.LocalPlayer |
Pros and Cons of Loops
Loops are very efficient ways of indexing tables, counting up or down, or smoothly CFraming
. They also minimize code, so you can do more with less.
Loops are also very resource consuming, depending on the loop. Do not ever do a loop without a wait() inside. This can cause studio to crash, and make you lose your hard work.