Corona – for loop

The for loop

Often when writing a program you will want to repeat the same process. Luckily there is a construct designed especially for this.

Meet the for loop

The for loop is a construct that repeats a block of code a set number of times. Here’s an example that counts from 1 to 10:

for count = 1, 10, 1 do
    print( “count:”, count )

Here count is a variable assigned a starting value of 1. 10 is defined as the ending value for count. And, 1 is the value that will increment count with each repeat. That is 1 will be added to count with each repeat.

The code between do and end is repeated with each count.

The variable used to keep track of the loop can use any name you like. For example you’ll often see i used here.

for i = 1, 12, 1 do
    print( “Count:”, i )

Essentially the loop counts from the first number to the second number, adding or stepping with the third number.

Count backwards

For loops can count forward or backward. Try this example:

for count = 10, 1, -1 do
    print( “Count:”, count )

This time the loop starts at 10 and counts by subtracting 1 each time until count reaches a value of 1.

Stepping by values other than 1

The step can also be any value you like. For example:

for count = 2, 10, 2 do
    print( “Count:”, count )

This time the loop begins the count on 2, and steps 2 with each repeat, counting the event numbers from 2 to 10.

A few notes on loops

When a loop is run the computer does not up the screen. Therefore you can not use a loop to animate objects! All other processes are suspended until the loop completes.

That said you can use a for loop inside of an enterFrame handler to animate a list of objects.

Why use a loop?

Many times you will have lists of things to work with. Imagine a game like Tetris. A for loop makes a good choice for updating all of the tiles on the board when the game updates.

Space Invaders type games might use a for loop to loop through all of the invaders to move and check for collisions.

Any program might us a for loop to loop through a list of display objects to position and initialize them when the program begins.

Leave a Reply

Your email address will not be published. Required fields are marked *