Arithmetic Shortcuts
Part of the Fundamentals section of Coddy's GDScript journey. Lesson 18 of 92.
Games often update a variable from its own value: add points to a score, remove hp after a hit.
var score := 10
score = score + 5 # score holds 15The shortcut += does the same with less code:
var score := 10
score += 5 # score holds 15Every arithmetic operator has a shortcut:
+=adds:score += 5-=subtracts:hp -= 3*=multiplies:damage *= 2/=divides:speed /= 2%=keeps the remainder:turn %= 4**=raises to a power:size **= 2
The rules of each operator still apply. When hp holds the integer 10, hp /= 4 drops the decimal part and hp becomes 2.
+= also works on strings, where it adds text to the end:
var greeting := "Hero"
greeting += "!"
print(greeting) # Hero!Challenge
EasyThe variable count starts at 0. Using the shortcuts, add these operations in this order:
- Add
4tocount - Multiply
countby2 - Subtract
1fromcount
Keep the declaration of count. The print() line outputs:
count = 7Try it yourself
extends Node
func _ready():
var count := 0
# Add the three operations below
# Don't change the line below
print("count = ", count)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsInteger DivisionModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators10Functions
Declare a FunctionArgumentsReturnReturn TypesRecap - Sigma FunctionRecap - Validation FunctionDefault Values5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary OperatorPractice on your own: Online GDScript compiler