Loops

Loops are one of the basic constructs in a language. So, let's see the loops that haXe supports.

While

While is a loop that is executed as long as a condition is true. It has the following two syntaxes:

while(condition) exprToBeExecuted;
doexprToBeExecuted while(condition);

With the first syntax, the condition is tested before entering the loop. That means, if the condition is not true, exprToBeExecuted will never be executed.

With the second syntax, the condition is tested after the execution of exprToBeExecuted. This way, you are sure that exprToBeExecuted will be executed at least once. The following are two simple examples to help you understand how these syntaxes have to be used:

public static function main()
{
var i : Int = 0;
while(i< 18)
{
trace(i); //Will trace numbers from 0 to 17 included
i++;
}
}

The preceding code is for the first syntax, and now, the second syntax:

public static function main()
{
var i : Int = 0;
do
{
trace(i); //Will trace numbers from 0 to 17 included
i++;
} while(i< 18);
}

The following is the trace from it:

TesthaXe.hx:9: 00

TesthaXe.hx:9: 1

TesthaXe.hx:9: 2

TesthaXe.hx:9: 3

TesthaXe.hx:9: 4

TesthaXe.hx:9: 5

TesthaXe.hx:9: 6

TesthaXe.hx:9: 7

TesthaXe.hx:9: 8

TesthaXe.hx:9: 9

TesthaXe.hx:9: 10

TesthaXe.hx:9: 11

TesthaXe.hx:9: 12

TesthaXe.hx:9: 13

TesthaXe.hx:9: 14

TesthaXe.hx:9: 15

TesthaXe.hx:9: 16

TesthaXe.hx:9: 17

For

haXe has a for loop that only supports working on iterators. An iterator is an object that supports some methods defined in the iterator typedef. It holds several values and returns them one by one at each call of the next function. The following is an example of a for loop:

for(i in 0...10)
{
trace(i); // Will trace numbers from 0 to 9
}

0...10 is a special construct. The ... operator takes two integers and returns an iterator that will return all integers from the first one (included) to the last one (excluded).

The following is the printed text if you do not trust me:

TesthaXe.hx:8: 0

TesthaXe.hx:8: 1

TesthaXe.hx:8: 2

TesthaXe.hx:8: 3

TesthaXe.hx:8: 4

TesthaXe.hx:8: 5

TesthaXe.hx:8: 6

TesthaXe.hx:8: 7

TesthaXe.hx:8: 8

TesthaXe.hx:8: 9

This construct is particularly useful to iterate over arrays and lists. That's something we will see when we discuss arrays and lists, but the following is an example of it:

class TesthaXe
{
public static function main(): Void
{
var l = new List<String>();
l.add("Hello");
l.add("World");
for(s in l)
{
neko.Lib.println(s);
}
}
}

This code will print Hello at first and then World because it will iterate over the elements of the l list.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.42.116