The "For" Statement

This section explains the use of "for".

A "for" statement has this form:

GML Code Example

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:

  • The first statement initializes the for-loop.
  • The expression tests whether the loop should be ended.
  • Statement2 is the "step" statement that goes to the next loop evaluation.

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:

GML Code Example

{
 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.





No Examples Submitted

Does this page need better examples? Be the first to Submit

No Edits Suggested

Is this page unclear or not descriptive enough? Suggest an edit to the page and with enough upvotes your changes will be made.

No Questions Have Been Ask

Do you have a question about this page? Ask it Here