Game Development Reference
In-Depth Information
The while loop
The
while
loop is a loop that repeats as long as a statement evaluates as true. This state-
ment can be made of a function or an equation, and as long as the statement evaluates as
true, the code in the curly braces that follow will be repeated.
This is a
while
loop in GML.
As you can see, the
while
loop is structured much the same as an
if
statement. Except,
instead of saying,
if
something is happening, do something, we are saying,
while
something is happening, do something.
In this case, we are saying
while (x<100)
; add
1
to
x
.
As long as the statement returns true, the code will be repeated. If the object's
x
was equal
to
0
before the
while
statement was run, then the code will repeat 100 times as one is
added to
x
at every run.
Once
x
is over 100, the statement is no longer true and the loop stops.
It is important to be careful with this type of loop. If, for example, we accidentally typed
x-=1
and we subtracted 1 from
x
at every run, your game would freeze until the operat-
ing system detects it as being unresponsive. This is what is called an infinite loop. An in-
finite loop is a loop that has no exit. It causes the game to loop through the one piece of
code forever, and as this happens in the same step, the game will never progress any fur-
ther.
The for loop
The
for
loop is the most complicated but also one of the most commonly used loops.
The
for
loop is often used to apply a change to many instances at once.
This is what a
for
loop looks like in GML: