TExcelTAD
Home › Godot 4 with GDScript › GDScript Syntax

GDScript Syntax

GDScript is Godot's own scripting language. It looks like Python (indentation instead of braces, var, func, if ... :), but it is built for the engine: every script is a class, vectors and colors are built-in types, signals and node paths are part of the syntax, and optional static types make it faster and safer. If you know Python, expect a few surprises listed at the end of this lesson.

The examples here are extends SceneTree scripts: the code in _init() runs once, and quit() ends the program.

Variables, constants and types

gdscript · try it yourself
extends SceneTree

const MAX_LIVES = 3            # constants are evaluated when the script compiles

func _init():
	var player_name = "Ada"    # dynamic: can hold any type later
	var lives := MAX_LIVES     # inferred static type: int, and it stays int
	var speed: float = 120     # explicit type; 120 is converted to 120.0
	var alive: bool = true
	var spawn := Vector2(32, 64)

	print(player_name, " has ", lives, " lives")
	print("speed = ", speed, ", alive = ", alive, ", spawn = ", spawn)
	print(type_string(typeof(lives)), " ", type_string(typeof(speed)), " ", type_string(typeof(spawn)))
	player_name = 42           # allowed: player_name has no static type
	print(player_name)
	quit()
Ada has 3 lives
speed = 120.0, alive = true, spawn = (32.0, 64.0)
int float Vector2
42
  • var x = ... is dynamic. var x := ... infers a static type from the value; var x: float = ... declares it. Typed variables are checked when the script loads and run faster; Static Typing covers them in depth.
  • Indentation uses tabs by default (spaces work if you are consistent). Comments start with #; ## comments are documentation comments that show up in the editor's help.
  • print() joins its arguments with no separator. prints() adds spaces, printt() tabs.

Numbers and operators

int is a 64-bit integer, float a 64-bit double. Operators follow C more than Python:

gdscript · try it yourself
extends SceneTree

func _init():
	print(7 / 2, " ", 7 / 2.0, " ", 7.0 / 2)        # int / int is integer division
	print(7 % 3, " ", -7 % 3, " ", posmod(-7, 3))   # % keeps the sign; posmod doesn't
	print(fmod(7.5, 2.0), " ", 2 ** 10)
	print(int(3.9), " ", round(2.5), " ", floor(-1.5), " ", snappedf(3.14159, 0.01))
	print(clamp(150, 0, 100), " ", lerp(0.0, 10.0, 0.25), " ", abs(-4))
	print(0.1 + 0.2 == 0.3, " ", is_equal_approx(0.1 + 0.2, 0.3))
	var hp := 10
	hp -= 3
	hp *= 2
	print("hp = ", hp)
	print(true and not false, " ", 3 > 2 or false, " ", "x" in "xyz")
	quit()
3 3.5 3.5
1 -1 2
1.5 1024
3 3.0 -2.0 3.14
100 2.5 4
false true
hp = 14
true true true
  • 7 / 2 is 3 when both sides are int. Write 7 / 2.0 or float(a) / b for a fractional result (the editor warns about integer division).
  • -7 % 3 is -1. For wrapping indices (a tile on a looping map, a menu that cycles) use posmod (int) or fposmod (float).
  • Compare floats with is_equal_approx, never ==.
  • Logic uses words (and, or, not) or symbols (&&, ||, !); the words are the official style.

Control flow

gdscript · try it yourself
extends SceneTree

func grade(score: int) -> String:
	if score >= 90:
		return "S"
	elif score >= 70:
		return "A"
	else:
		return "B"

func describe(value) -> String:
	match value:
		0:
			return "zero"
		1, 2, 3:
			return "small"
		"boss":
			return "a boss name"
		[var x, var y]:
			return "a pair %s, %s" % [x, y]
		_:
			return "something else"

func _init():
	print(grade(95), grade(70), grade(10))
	for i in 3:                       # 0, 1, 2
		print("wave ", i)
	for i in range(10, 0, -4):        # 10, 6, 2
		print("countdown ", i)
	var fuel := 3
	while fuel > 0:
		fuel -= 1
		if fuel == 1:
			continue
		print("fuel ", fuel)
	for v in [2, "boss", [4, 5], 9.5]:
		print(v, " -> ", describe(v))
	var label := "ready" if fuel == 0 else "flying"   # conditional expression
	print(label)
	quit()
SAB
wave 0
wave 1
wave 2
countdown 10
countdown 6
countdown 2
fuel 2
fuel 0
2 -> small
boss -> a boss name
[4, 5] -> a pair 4, 5
9.5 -> something else
ready
  • for i in 3 counts 0..2; range(start, end, step) works like Python's.
  • match replaces switch. Patterns can be values, several values separated by commas, arrays and dictionaries with bindings (var x), and _ as the wildcard. There is no fall-through.
  • The conditional expression is a if condition else b, as in Python.

Functions and lambdas

gdscript · try it yourself
extends SceneTree

func damage(hp: int, amount: int = 1, armor := 0) -> int:
	return max(hp - max(amount - armor, 0), 0)

func greet(who: String) -> void:
	print("Hello, ", who)

func _init():
	print(damage(10), " ", damage(10, 4), " ", damage(10, 4, 3))
	greet("Godot")

	var double := func(x): return x * 2         # a lambda (an anonymous function)
	print(double.call(21))

	var on_hit: Callable = damage                 # a method used as a value
	print(on_hit.call(5, 2))

	var count := 0
	var add := func(): count += 1                 # lambdas capture variables by value
	add.call()
	print("count is still ", count)
	quit()
9 6 9
Hello, Godot
42
3
count is still 0
  • Parameters can have types and defaults; -> void declares that nothing is returned.
  • Functions are first-class: a method name without parentheses is a Callable, and so is a lambda. Signals use exactly this (button.pressed.connect(_on_pressed)).
  • Lambdas capture local variables by value, so count += 1 inside the lambda changed a copy. To share state, capture an array or dictionary, or use a member variable.

Coming from Python

Python GDScript
def f(x): func f(x):
None, True null, true
elif, and/or/not the same
7 // 2 7 / 2 (when both are int)
f-strings "%s has %d" % [name, n] or "{a}".format({"a": 1})
self.x required self is optional: x means the member
__init__ _init()
list comprehension array.map(func(x): return x * 2)
exceptions (try) none: functions return error codes (OK, ERR_FILE_NOT_FOUND) or null

GDScript has no exceptions. A runtime error (calling a method on null, an index out of range) prints an error, stops the current function and the game keeps running; in the editor, the debugger pauses on it. Check values instead of catching errors: if node:, if index < array.size():, if err != OK:.

Test yourself

What does print(7 / 2) print in GDScript?

  1. 3.5
  2. 3
  3. 4
  4. An error

What is the difference between var a = 5 and var a := 5?

  1. None
  2. := gives a the static type int; = leaves it dynamic
  3. := makes a constant
  4. := copies the value

How do you handle a possible failure in GDScript, which has no try/catch?

  1. Wrap it in try:
  2. Check return values and null before using them (if err != OK, if node:)
  3. Use except
  4. Errors can't happen in GDScript