GM: Loops

From GMpedia.org Wiki

Jump to: navigation, search

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

Contents

[edit] The for-loop

The for-loop has the following syntax:

for(<statement1>;<expression>;<statement2>)
{
 <execute code>
}

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<ds_list_size(items);i+=1)
draw_text(5,5+i*15,ds_list_find_value(items,i));

[edit] Explanation

i=0: indicates that the value i will start counting at 0

i<ds_list_size(items): the action needs to be performed as long as there are still items to be drawn => <expression> indicates the condition to be met to be able to perform <statement2>

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. => <statement2> indicates how many to add

[edit] The do-until loop

The do-until loop has the following syntax:

do
{
 <execute code>
}
until (<expression>)

First, the code is executed once. Then the until <expression> 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.

[edit] The while loop

The while loop has the following syntax:

while (<expression>)
{
 <execute code>
}

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.

[edit] The repeat loop

The repeat loop has the following syntax:

repeat (<number>)
{
 <execute code>
}

A piece of code is executed <number> times.

[edit] See Also

Personal tools