The "For" Statement

This section explains the use of "for".

A "for" statement has this form:

for (<statement1> ; <expression> ;<statement2>) <statement3>


This works as follows - First statement1 is executed, then the expression is evaluated and, if it is true, statement 3 is executed. Then statement 2 and then the expression is evaluated again. This loop will continue until the expression is found to be false.

Now, this may sound complicated when written like that, but you should interpret it as:

This extremely useful for doing repetitive tasks that would involve multiple lines of code in any other way, and is commonly used as a counter for evaluating arrays, or drawing things. the following code example illustrates a typical use for this type of statement:

{
var i;
for (i = 0; i < 10; i += 1)
   {
   draw_text(32, 32 + (i * 32), string(i) + ". "+ string(scr[i]));
   }
}


The above code initialises a for loop, starting at 0 and counting up until 9, and then uses the loop value of "i" to draw the values stored in an array down the screen. Note how the "for" loop variable "i" is used to not only loop through the array, but to draw a number as well as tell GameMaker: Studio where to draw the values to in the room. This flexibility is one of the main reasons why "for" loops are so important in programming.


Back: GML Overview
Next: The "Switch" Statement
© Copyright YoYo Games Ltd. 2018 All Rights Reserved