A program is a sequence of instructions that Sugar runs from top to bottom. A Sugar text block can contain a small program:
text {
let basePower = 8;
let bonus = 3;
let totalPower = basePower + bonus;
"@1 attacks with {totalPower} power."
}
Sugar creates basePower, then bonus, then totalPower. The final string becomes the message.
Statements and final expressions
A statement is an instruction performed by a program. These three declarations are statements:
let basePower = 8;
let bonus = 3;
let totalPower = basePower + bonus;
Each ends with ;. A line break is only spacing; it does not finish a statement.
The last line of a value-producing block is different:
"@1 attacks with {totalPower} power."
It has no semicolon because it is the block’s final expression. Its value becomes the value produced by the entire block.
Declare a temporary variable
let creates a variable that exists only while the current program runs:
let totalPower = basePower + bonus;
The declaration has the same basic shape as var: a keyword, a name, =, an initial value, and a semicolon. Its lifetime is different. A let variable disappears when its surrounding program finishes.
Use let for an intermediate result that does not belong to the creation’s lasting state:
text {
let subtotal = price * quantity;
let finalPrice = subtotal - discount;
"The final price is {finalPrice}."
}
Scope inside a block
A variable name is available only inside the region where it is declared. This region is its scope.
text {
let greeting = "Welcome back";
"{greeting}, @1!"
}
greeting exists from its declaration to the end of this text block. Code outside the block cannot read it.
Top-level var declarations have a wider scope: every text, function, and Item action in the same Code module can use them.
The next lesson changes mutable variables with assignment statements.