Working with Loops

From Game Editor

Jump to: navigation, search

The loop is one of the most useful functions that exists in programming.

There are 3 types of loops: for, while, and do.

For Loops

The basic structure of a for loops is this: (starting value, ending value, increment).

To start you need a local variable to loop with; here is a sample loop;

 int i;
 for(i=0; i<100; i++){

What this will do is intialize i at a value of 0. It will perform the action until i=99; and each time it loops, it will increase i by 1.


 for(i=0; i<50; i++){

is the same as

 for(i=0; i<99; i+=2){

except, the value of i in the bottom loop with be double the value in the top loop; However, each loop will run 50 times exactly.

Not only can you perform repeated actions using this, but you can use the value of i for all sorts of things. For instance

 for(i=0; i<100; i++){
 CreateActor("object", "anim1", "(none)", "(none)", i*32, 100, true);

Each new actor created in that loop will appear 32 pixels to the right of the previous actor created, because we asked for (i*32) as our x, and i will increase once each time.

When creating puzzle pieces, or buttons on a keypad, you can use other variables in combination with the loop; example:

 int i=0; int j=0; int k=0;
 for(i=0; i<20; i++){
 CreateActor("object", "anim1", "(none)", "(none)", j*32, k*32, true);
 j=0; k++;

Each time in the loop, j will increase, but when it reaches 5 it resets and k increases. Thus this loop would create a grid of objects 5 wide and 4 tall, for a total of 20 objects.

The reason it's called a for loop is "do this FOR this many repetitions".

Note that not only can for loops be reversed, but they can also use different variables to determine their starting and stopping. Here are two examples:

 int i;
 for(i=100; i>0; i--){
 }  //runs in reverse

 int i; int j=100;
 for(i=0; i<j; i++){
 } //will run till the value of J is reached.

While and do loops have their uses, but beginners should stick to for loops as they are safer; if you write while loops incorrectly, your program will freeze/hang.