An if statement runs a block only when its condition is true:
if health <= 0 {
status = "DEFEATED";
}
The condition follows if. The braces contain the branch controlled by that condition.
Choose between two branches
Add else for the false case:
if score >= goal {
result = "WIN";
} else {
result = "TRY_AGAIN";
}
Exactly one branch runs. The program continues after the complete statement.
Here is the same decision inside a complete Boop module:
var score: number = 0 with {
input: true,
min: 0,
};
text {
let result = "Try again";
if score >= 10 {
result = "You win";
}
"{result}, @1!"
}
Add more branches
Use else if when the decision has several ordered cases:
if health <= 0 {
status = "DEFEATED";
} else if health < 25 {
status = "CRITICAL";
} else {
status = "READY";
}
Sugar checks the conditions from top to bottom and runs the first matching branch.
Produce a value with if
When the decision itself should be an expression, use then and else:
let label = if score >= 10 then "Winner" else "Challenger";
This is a value-form if expression. Both branches produce a value, and that value is stored in label.
The same form can be used directly with Sugar text formatting:
text "@1 lands {}." with if critical then "a critical hit" else "a normal hit";
Use brace branches when code must run statements. Use if condition then value else value when one expression needs to choose a value.
The next lesson introduces functions: named operations that accept information and may produce a result.