Iteration in for statements

There are several ways to iterate through members of a list or array using the for statement.

Use automatic iteration to iterate through a collection, such as a number sequence, an array, or a list. Iteration starts with the initial value or member, and continues sequentially until terminating at the last value or member.

Collection iteration with a variable

The standard form of iteration is to use an iteration variable. Use the following syntax:

for (member in OBJ) { ... }

The following lines show examples of iterating over a collection by using a variable:

for (prop in myListOfProperties)
for (name in {"John", "Mary", "David"})
for (i in 0..|100) // i iterates through the values 0 to 99

Iteration with no variable for numerical intervals only

If the object to loop across is a numerical iterator type, the variable declaration is optional. For example:

for (1..10) { 
  print("hello!") 
}

Iteration with an index

Use index iteration if you need to determine the exact position of a particular element within an array or list. This technique adds an explicit variable to contain the index value. This can be useful to read members of the array or list in a non-sequential fashion using array notation. Specify iteration with an index variable with the following syntax:

for (member in OBJ index loopcount)

Example:

// This code prints the index of the highest score in an array of test scores. 
// This particular example prints "3".

var testScores = new int[] {91, 75, 97, 100, 89, 99}
print(getIndexOfHighestScore(testScores))

function getIndexOfHighestScore(scores : int[]) : int {
  var highIndex = 0

  for (score in scores index i) {
    if (score > scores[highIndex]) { highIndex = i }
  }

  return highIndex
}

The result of running this code is the following line:

3

Iteration with an iterator

Use this type of iteration if you need to access the functionality of the iterator that processes the items in an array or collection. The iterator is only available if the expression that the for loop evaluates is an iterable type. For example, the iterator is not available if the expression is a String, as shown in the following line:

for (letter in "abcde")

You can use the hasNext method on the iterator to determine whether the for loop is processing the last item.

Most collections do not support modification during iteration and throw a ConcurrentModificationException on attempted modifications. Gosu does supports object removal by using the remove method on the iterator loop variable, as shown in this example:
var strs = {"a", "b", "", "c"}
for (c in myList iterator iter) {
  if (c.length() == 0) {
    iter.remove()
  } else {
  ...
  }
}
for (c in strs) {
  print(c)
}
The output from this code is the following:
a
b
c