Menu
CoddyTech

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 15

The shortcut += does the same with less code:

var score := 10
score += 5 # score holds 15

Every 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 icon

Challenge

Easy

The variable count starts at 0. Using the shortcuts, add these operations in this order:

  1. Add 4 to count
  2. Multiply count by 2
  3. Subtract 1 from count

Keep the declaration of count. The print() line outputs:

count = 7

Try it yourself

extends Node

func _ready():
	var count := 0
	# Add the three operations below

	# Don't change the line below
	print("count = ", count)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Online GDScript compiler