for statements

The for statement block uses a multipart construction.

Syntax

for ( [var] identifier in expression [ index index-identifier ] [ iterator iterator-identifier ] ) { statements }

The scope of identifier is limited to the statement block itself. The keyword var before that local variable identifier is optional.

The expression expression in the in clause must evaluate to one of the following:

An array
An iterator
An object that implements the Java Iterable interface. Iteration starts with the initial member and continues sequentially until terminating at the last member.
A Java list or collection class, such as java.util.ArrayList
Iteration starts with the initial member and continues sequentially until terminating at the last member.
A String object
Gosu treats the string as a list of characters.
A Gosu interval

The iterator part is valid only for an expression that is iterable.

The number of times that Gosu executes the statements in the body of the loop block depends on the value of the expression and on the start and end values of the iterator:
  • If the expression evaluates at run time to null, the body of the loop block is not executed.
  • If the start and end values of the iterator are identical, the for loop is executed once.
  • The loop is executed the same number of times if the iterator's start and end values are reversed. If the start value is greater than the end value, the looping variable subtracts from the start value until the end value is reached.

Gosu provides backwards compatibility for the use of an older Gosu style foreach statement. Better style is to use the for statement instead.

See also