Version: v0.6.1 - Beta.  We welcome contributors & feedback.  THanks!


Foreach Loops 

A foreach loop repeats the same block of code multiple times.

They are most commonly used to iterate over a List.

$colors = ['Red', 'Blue', 'Yellow'];

// 'color' holds the value of the current
// element in the loop.
foreach $colors as $color {
    print($color ~ ' is a primary color.');
//= 'Red is a primary color'
//= 'Blue is a primary color'
//= 'Yellow is a primary color'

// Loop over a range of numbers
foreach range(1, 3) as $n {
//= 1
//= 2
//= 3

Looping Over a Map

You can also loop over the key/value pairs of a Map.

Use a comma , to create a variables for the current key and value.

$countryCodes = {
    US: 'United States',
    FR: 'France',
    JP: 'Japan',

foreach $countryCodes as $code, $name {
    print($code ~ ' is the code for ' ~ $name);
//= US is the code for United States
//= FR is the code for France
//= JP is the code for Japan

Loop Control

Use break to immediately exit a loop. The program will jump to the end of the block and resume.

Use continue to skip the current cycle of a loop. It will immediately jump to the top of the block and resume the next cycle.

$lines ='quotes.txt');

// Find the 1st quote that refers to 'inspiration'
foreach $lines as $line {
    if $line.contains('inspiration') {
        break;  // end the loop

Infinite Loops

The loop statement will keep repeating until you exit via break.

This is useful when you don’t know how many times it will repeat.

// Print all quotes that refer to 'creativity'
$file ='quotes.txt');
loop {
    $line = file.readLine();
    if $line == false {
        break; // end of file
    else if $line.contains('creativity') {

BackgroundOther languages achieve this with the while and do/while commands. THT's flatter approach avoids some common pitfalls with those commands, such as off-by-one bugs.