Loops

When repeating an action multiple times, you need to use loops. Game Maker supports many types of loops.

The following loops are supported by Game Maker:


 * for
 * do-until
 * while
 * repeat

The for-loop
The for-loop has the following syntax:

for { }

An example will make this more clear. Suppose you have five items in a list called items (the list data structure). You want to draw these on screen, with a distance between each of 15 pixels. Normally, you would use the following piece of code:

draw_text(5,5,ds_list_find_value(items,0)); draw_text(5,20,ds_list_find_value(items,1)); draw_text(5,35,ds_list_find_value(items,2)); draw_text(5,50,ds_list_find_value(items,3)); draw_text(5,65,ds_list_find_value(items,4));

This is a rather long piece of code for an action that is each time almost identical.

As you can see, the first item is drawn at an y position of 5 pixels and for each item 15 pixels are added. So for each item in the list, the y value is equal to 5+(its position in the list)*15. The x value remains the same, of course.

With a for loop, you can do all this code in two lines as follows:

for(i=0;i indicates the condition to be met to be able to perform

i+=1: each time, a new item is drawn. Suppose you would add 2 to i each time, then all items with an even index would be drawn. => indicates how many to add

The do-until loop
The do-until loop has the following syntax:

do { } until

First, the code is executed once. Then the until code comes up. If the expression is true, the code is executed again. As long as the expression remains true, the code will be executed. The expression is a condition that needs to be met for the code to be allowed to be executed.

The while loop
The while loop has the following syntax:

while { }

First, the expression is tested. If it is true, the code is executed. Now the expression will be checked again. If true, the code is executed. As long as or "while" the expression is true, the code is executed.

The repeat loop
The repeat loop has the following syntax:

repeat { }

A piece of code is executed times.