Conditionals

Control the flow of your program with if and else.

The if statement

Execute code when a condition is true:

fn main() {
    5 3 > if {
        "5 is greater than 3" print nl
    }
}

The if pops a value from the stack. If non-zero (true), it executes the block.

if-else

Handle both cases:

fn main() {
    10 -> x

    x 5 > if {
        "x is greater than 5" print nl
    } else {
        "x is 5 or less" print nl
    }
}

Conditional expressions

if can leave values on the stack:

fn abs(x:i64 -- result:i64) {
    -> x  // bind parameter
    x 0 < if {
        x neg
    } else {
        x
    }
}

fn main() {
    -5 abs print nl  // 5
    7 abs print nl   // 7
}

Both branches must leave the same number of values on the stack.

Combining conditions

Use logical operators:

fn main() {
    18 -> age
    1 -> has_id

    // AND: both must be true
    age 18 >= has_id and if {
        "Can enter" print nl
    }

    // OR: either can be true
    age 21 >= age 18 < or if {
        "Special case" print nl
    }

    // NOT: invert condition
    has_id 0 == if {
        "No ID" print nl
    }
}

Comparison operators

Operator Meaning
== Equal
!= Not equal
< Less than
<= Less or equal
> Greater than
>= Greater or equal
fn main() {
    5 5 == if { 
        "equal" print nl
    }
    5 3 != if {
        "not equal" print nl
    }
    3 5 < if {
        "less than" print nl
    }
}

Common patterns

Guard clauses

fn process(x:i64 -- result:i64) {
    -> x  // bind parameter
    x 0 < if {
        0
        return // Early return for invalid input
    }
    x dup *    // Normal processing
}

Default values

fn get_or_default(value:i64 default:i64 -- result:i64) {
    -> default -> value
    value 0 == if {
        default
    } else {
        value
    }
}

Range checking

fn is_valid_age(age:i64 -- valid:i64) {
    -> age  // bind parameter
    age 0 >= age 150 <= and
}

fn main() {
    25 is_valid_age print nl   // 1 (true)
    -5 is_valid_age print nl   // 0 (false)
    200 is_valid_age print nl  // 0 (false)
}

What's next?

Learn about Loops to repeat operations, or Switch for multi-way branching.