日本語

Control Flow

This section explains the syntax for describing program control flow in LuneScript.

if statement

Performs conditional branching. It can be followed by elseif or else blocks.

let val = 10;
if val == 1 {
    print( "val is 1" );
} elseif val == 10 {
    print( "val is 10" );
} else {
    print( "other" );
}

In LuneScript, if the result of an expression is nil or false, it is considered "failing". Otherwise, it is "passing".

Comparing bool values with == true or == false is not recommended. Use if exp or if not exp instead.

switch statement

Performs branching based on a value. Although Lua does not have this syntax, it is supported in LuneScript.

let val = 1;
switch val {
    case 1 {
        print( "One" );
    }
    case 2, 3 { // Multiple values can be specified
        print( "Two or Three" );
    }
    default {
        print( "Other" );
    }
}

Integration with Enum: When the conditional expression is an Enum value, the compiler checks if all cases are covered. If all cases are described, default is considered unreachable, and describing it results in a warning (use _default if you want to describe it as a fail-safe).

match statement

Performs pattern matching on alge type values, extracts values, and performs branching.

alge Result {
    Val( int ),
    Err( str ),
}
fn check( res: Result ) {
    match res {
        case .Val( val ) {
            print( "Success:", val );
        }
        case .Err( msg ) {
            print( "Error:", msg );
        }
    }
}

For more details on alge types, see the Values and Types chapter.

while statement

Repeats the loop as long as the condition is met.

let mut val = 0;
while val < 5 {
    print( val );
    val = val + 1;
}

To create an infinite loop, use while true { ... }. This true must be a literal (constant variables are not allowed).

repeat statement

Repeats the loop until the condition is met (while it is not met). The condition is checked after the block is executed.

let mut val = 0;
repeat {
    val = val + 1;
} val >= 5;

Variables declared within the block can be used in the termination condition expression.

* Note: repeat may be deprecated in the future.

for statement

Performs a loop over a range of numbers.

// Increase from 1 to 10 by 1
for i = 1, 10 {
    print( i );
}

// Decrease from 10 to 1 by -1
for i = 10, 1, -1 {
    print( i );
}

The format is for variable = start, end [, step] { ... }. If the step is omitted, it defaults to 1.

foreach statement

Iterates over the elements of a collection (List, Map, Set).

let list = [ 10, 20, 30 ];
foreach val, index in list {
    print( index, val ); // 1 10, 2 20, 3 30
}

let map = { "a": 1, "b": 2 };
foreach val, key in map {
    print( key, val );
}

apply statement

Used when using Lua iterator functions (equivalent to Lua's for in).

apply txt of string.gmatch( "a.b.c", "[^%.]+" ) {
    print( txt );
}