Control Statements - mfichman/jogo GitHub Wiki

Loops

Jogo has two types of loops: the for loop, and the while loop:

for value in collection {
    print(value)
}

while condition {
    print("hello")
}

The while loop is simple: it repeats until condition is false. The for loop is special. If collection implements the Iterable interface, then the loop will repeat once for each value (value) in collection. Interfaces will be discussed in a later section.

Conditionals

Conditional statements are used to express decisions:

if expression {
    block1
} else {
    block2
}

The expression is evaluated, and if it is true, then block1 is executed. Otherwise, block2 is executed. Note that the brackets ({ }) are always required for conditionals.

Case statements

Case statements are very similar to conditionals, but can sometimes be more compact:

case expression {
    when case1 { block1 }
    when case2 { block2 }
    ...
    when caseN { block N }
}

Here, expression is evaluated once, and then its value is compared with the cases case1..caseN in order. The comparison stops when expression is equal to one of case1...caseN, and then no more cases are evaluated.

Reading lines from a file

A for loop can be used to easily read lines from a file:

main() Int {
    for line in File::open('test.txt').lines {
        print(line)
    }
    return 0
}

The function main is where the program begins executing. Inside main, a for loop reads each line from a file named "test.txt", and prints each line to the console. The statement return 0 returns an Int from the function.