Skip to content

if

Syntax

if (<predicate>) {
    <statement>
    ...
}
if (<predicate>) {
    <statement>
    ...
}
else {
    <statement>
    ...
}

Parameters

<predicate>
A truthy or falsey numeric expression.
<statement>
A valid FRED statement, such as an action or an assignment.

Description

Conditionally execute one or more actions.

The agent executes the given statements when the predicate provided evaluates to a non-zero value (true). The predicate is evaluated with respect to the current agent. In this manner, an if statement allows individual agents to behave differently within the same state.

Multiple statements can appear sequentailly within an if statement, including more if statements.

If the predicate evaluates to false, it will proceed to execute the statements inside of the else block, if specified.

Truthy and Falsey Values

Like in many programming languages, FRED's numeric expressions can be evaluated as either true or false. Values that evaluate to true are considered "truthy", and values that evaluate to false are considered "falsey".

In FRED, a value of 0 is falsey, and all non-zero values are truthy.

Examples

This example prints "I am rich!" if the shared numeric variable lotto_winnings contains a value of at least 1,000,000. If it's at least 1,000,000,000, it also prints "Very rich!".

If the lotto_winnings variable is less than 1,000,000, the agent prints "I am less rich".

state Demo {
    if (lotto_winnings >= 1000000) {
        print("I am rich!")
        if (lotto_winnings >= 1000000000)
        {
            print("Very rich!")
        }
    }
    else {
        print("I am less rich")
    }
    ...
}

See Also