5.13 for

Haxe does not support traditional for-loops known from C. Its for keyword expects an opening parenthesis (, then a variable identifier followed by the keyword in and an arbitrary expression used as iterating collection. After the closing parenthesis ) follows an arbitrary loop body expression.

for (v in e1) e2;

The typer ensures that the type of e1 can be iterated over, which is typically the case if it has an iterator method returning an Iterator<T>, or if it is an Iterator<T> itself.

Variable v is then available within loop body e2 and holds the value of the individual elements of collection e1.

var list = ["apple", "pear", "banana"];
for (v in list) {
// apple
// pear
// banana
Range iteration

Haxe has a special range operator to iterate over intervals. It is a binary operator taking two Int operands: min...max returns an IntIterator instance that iterates from min (inclusive) to max (exclusive). Note that max may not be smaller than min.

for (i in 0...10) trace(i); // 0 to 9

The type of a for expression is always Void, meaning it has no value and cannot be used as right-side expression. However, we'll later introduce array comprehension, which lets you construct arrays using for expressions.

The control flow of loops can be affected by break and continue expressions.

for (i in 0...10) {
  if (i == 2) continue; // skip 2
  if (i == 5) break; // stop at 5
// 0
// 1
// 3
// 4
since Haxe 4.0.0
Key-value iteration

In Haxe 4 it is possible to iterate over collections of key-value pairs. The syntax is the same as regular for loops, but the single variable identifier is replaced with the key variable identifier, followed by =>, followed by the value variable identifier:

for (k => v in e1) e2;

Type safety is ensured for key-value iteration as well. The typer checks that e1 either has a keyValueIterator method returning returning a KeyValueIterator<K, V>, or if it is a KeyValueIterator<K, V> itself. Here K and V refer to the type of the keys and the values, respectively.

var map = [1 => 101, 2 => 102, 3 => 103];
for (key => value in map) {
  trace(key, value);
// 1, 101
// 2, 102
// 3, 103
Related content