A common need in programming is to repeat the same code multiple times. This functionality is available through using loops. There are four main loop functions in GML: do, while, for, and repeat. Each of these has its own strengths and weaknesses.
Processing data in ds lists or arrays.
Performing the same action multiple times.
Performing a calculation until it is true.
Drawing data from lists, grids, or arrays.
A loop can result in many similar actions being executed in a very short time.
It is important to make certain that loops run the correct number of times and then stop. It is possible through a coding mistake to create an infinite loop that runs forever. This will cause the game to stop working. Care needs to be taken to avoid this from happening.
Also note that a loop will complete itself within one frame of the game. If you are using large loops or using lots at a time, another approach may be required. For example, if you looped through a block of code 1000 times within a single frame, it may have undesired effects such as making your game stutter.
Repeat Loop
which would create five firework effects at once.
While Loop
This would repeat until a free space is found.
Ensure this loop will exit (complete) at some point, if not it will run continuously and freeze your game. As in the preceding example, ensure there are free places within the room.
For Loop
The preceding code will loop from 0 to 24 and then exit. It will place the numbers 0 to 24 within the array.
If you wanted to include the value 25 in the loop
you can use: i<=number
which would populate the array with values 0 to 25 inclusive.
Do Loop
will try random positions until a free space is found.
The do loop will always execute at least once, but in for or while, it can be skipped.
Basic Projects
- A)
While loop. Set an object that randomly chooses a random position within 100 pixels of another object. Allow spacebar to find a new location.
- B)
For loop. Make a list with 100 numbers in random order from 1 to 1000. Display this data on screen in four columns, in ascending order. Allow spacebar to choose a new set.
Advance Projects
- C)
Set four random points in the room. Make an object visit each of these locations. Spacebar to restart.
- D)
Make a system that takes in all the names of students in your class. Display onscreen in alphabetical order, one at a time every five seconds.
Useful Functions
There will be times when you may wish to exit a loop early, for example, when a certain condition or value is met. break allows to do this.
Summary
You now are now aware of some appropriate uses of loops and how they can be implemented. You understand how to add, change, process, and display data.