Learn SugarBeginner

Expressions and operators

Build values from calculations, comparisons, boolean logic, and other Sugar expressions.

An expression is code that produces a value. A literal such as 5 is an expression. So is a calculation such as 5 + 2, which produces 7.

An operator is a symbol or word that combines, compares, or changes the meaning of values.

Calculate numbers

score + bonus
health - damage
price * quantity
total / players

The arithmetic operators are:

OperatorMeaningExampleResult
+Addition8 + 210
-Subtraction8 - 26
*Multiplication8 * 216
/Division8 / 24
^Exponent2 ^ 38
modRemainder10 mod 31

Use parentheses to make one part happen first:

(score + bonus) * 2

Join strings

+ joins strings as well as adding numbers:

"Score: " + score

This is called concatenation. Prefer interpolation when building a Sugar message:

text "Score: {score}";

Concatenation remains useful when an expression itself must produce a string.

Compare values

A comparison is an expression that produces a boolean: either true or false.

OperatorQuestion
==Are the values equal?
!=Are the values different?
<Is the left number smaller?
<=Is the left number smaller or equal?
>Is the left number larger?
>=Is the left number larger or equal?

For example:

score >= 10
mood == "Playful"

Use == to compare values. The single = used in a declaration supplies or assigns a value; it does not ask a question.

String comparisons are case-sensitive. "Playful" and "playful" are different strings.

Combine boolean expressions

Use and when both sides must be true:

score >= 10 and lives > 0

Use or when either side may be true:

mood == "Playful" or mood == "Bold"

Use not to reverse a boolean:

not finished

If finished is false, not finished is true.

Use a condition

A condition is simply a boolean expression used to decide whether something is available or which code should run.

The when clause makes a text eligible only when its condition is true:

var mood: choice = "Playful" with {
  input: true,
  choices: ("Playful", "Bold", "Quiet"),
};

text when mood == "Playful" {
  "@1 is feeling playful."
}

text when mood != "Playful" {
  "@1 is keeping things calm."
}

The condition only calculates true or false. It does not change state or display anything by itself.

The next lesson puts expressions into programs containing several instructions.