Reversing interval order

Sometimes you want a loop to iterate across elements in an interval in reverse order. To do this iteration, reverse the values of the beginning endpoint and ending endpoint for the double period symbol.

Compare the following examples:

  • 0..5 represents the values 0, 1, 2, 3, 4, 5 in that order.
  • 5..0 represents the values 5, 4, 3, 2, 1, 0 in that order.

Internally, these intervals are the same objects but Gosu marks 5..0 as being in reverse order.

For example, this code iterates from 10 to 1, including the end points:

for( i in 10..1) {
  print ( i )
}

If you have a reference to a reversed interval, you can force the interval to operate in its natural order. In other words, you can undo the flag that marks the interval as reversed. Use the following syntax:

var interv = 5..0
var leftIterator = interv.iterateFromLeft()

The result is that the leftIterator variable contains the interval for 0, 1, 2, 3, 4, 5.

The iterate method, which returns the iterator, always iterates across the items in the declared order, either regular order or reverse, depending on your definition of the interval.