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:
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | Addition | 8 + 2 | 10 |
- | Subtraction | 8 - 2 | 6 |
* | Multiplication | 8 * 2 | 16 |
/ | Division | 8 / 2 | 4 |
^ | Exponent | 2 ^ 3 | 8 |
mod | Remainder | 10 mod 3 | 1 |
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.
| Operator | Question |
|---|---|
== | 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.