Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 36 ยท GDScript

GDScript Basics: Variables, Types and Operators

Learn GDScript 4 fundamentals: variables, constants, static typing with := and type hints, built-in types, operators, strings and formatting, with read-only code and a Python model.

GDScript is the language most Godot developers use. It is indentation-based like Python, but designed specifically for the engine: it understands nodes, signals and Vector2, and it supports optional static typing, which catches mistakes in the editor and makes code faster. This lesson covers variables, constants, types and operators.

GDScript only runs inside Godot, so the GDScript blocks below are read-only. The Python stand-ins mirror the rules (types, formatting, integer division) that are close in both languages. Where they differ, we say so.

Your first script, line by line

GDSCRIPT
extends Node2D

var health := 100
const MAX_HEALTH := 100

func _ready() -> void:
    print("Health: ", health, "/", MAX_HEALTH)
  • extends Node2D says which node type the script builds on. Every script file is a class.
  • var declares a variable; const a constant that cannot change.
  • Indentation (tabs by default) defines blocks. A colon starts a block.
  • Comments start with #. A doc comment starts with ## and shows in the editor help.
  • No semicolons are needed.

Variables and types

GDScript is dynamically typed by default, but you can add types for safety. All three lines below are valid:

GDSCRIPT
var a = 5              # untyped: can hold anything later
var b: int = 5         # explicit type
var c := 5             # inferred type (int); cannot later hold a string

Static types are recommended: errors such as assigning a string to an int appear while you type, autocomplete works better and typed code runs faster. A project setting under Debug > GDScript can warn about untyped declarations.

Common built-in types:

Type Example Notes
int 42 64-bit integer; 1_000_000 allowed, 0xFF hex
float 3.14 64-bit; 1e3 = 1000.0
bool true, false
String "hello" Unicode; 'single' quotes also work
StringName &"jump" Interned string for fast comparison (used by input actions, signals)
Vector2, Vector3 Vector2(1, 2) Positions, velocities
Color Color.RED, Color("#ff8800")
Array, Dictionary [1, 2], {"a": 1} See Collections
NodePath ^"Player/Sprite" A path to a node
Variant anything The "any value" type
null null No value

Declare class-level (member) variables at the top, inside functions for locals. A local variable exists only inside its block.

Constants and enums

GDSCRIPT
const GRAVITY := 980.0
const SPEEDS = [100, 200]          # constants can hold arrays (contents are still mutable in some cases)

enum State { IDLE, RUN, JUMP }     # IDLE = 0, RUN = 1, JUMP = 2
var state := State.IDLE

func describe() -> String:
    return State.keys()[state]     # "IDLE"

Name constants in UPPER_SNAKE_CASE, variables and functions in snake_case, classes and enums in PascalCase.

Operators

Arithmetic: + - * / % and ** (power). Be careful with division:

GDSCRIPT
print(7 / 2)       # 3    (integer division when both are int)
print(7 / 2.0)     # 3.5
print(7 % 3)       # 1
print(2 ** 10)     # 1024

Comparison: == != < > <= >=. Logic: and, or, not (also &&, ||, !). Assignment shortcuts: +=, -=, *=, /=. Bit operations: & | ^ ~ << >>.

Other useful operators:

GDSCRIPT
var name := "Ada"
if name in ["Ada", "Linus"]:       # membership
    print("known")

var kind := "big" if health > 50 else "small"     # ternary-style
var s := "HP: %d" % health                          # format operator

The int division surprise is the same as in many languages: 7 / 2 is 3. Convert one operand to a float when you want a fraction. Godot warns "Integer division, decimal part will be discarded" so you notice.

Type conversion

GDSCRIPT
var n := int("42")            # 42
var f := float("3.5")         # 3.5
var s := str(42)              # "42"
var i := int(3.9)             # 3 (truncates)
var r := roundi(3.5)          # 4 (rounds)

Use is_valid_int() and is_valid_float() on strings before converting user input. Use typeof(x) to ask for a Variant's type, and x is Node2D to test class membership.

Strings

GDSCRIPT
var line := "Score: " + str(120)
var greeting := "Hello, %s! You have %d coins." % ["Ada", 7]
var padded := "%05d" % 42                 # "00042"
var price := "%.2f" % 3.14159             # "3.14"
var parts := "a,b,c".split(",")           # ["a", "b", "c"]
print("hello".to_upper(), "  x ".strip_edges())
print("abc".length(), "abc"[1])           # 3 b
var multi := """Line one
Line two"""

The newer String.format and the % operator are both fine. Use str() to join values of different types. print accepts many arguments and puts them together without spaces, while prints separates with spaces.

Scope and naming

A variable declared inside if or for lives in that block. A member variable (declared outside functions) is available to the whole script and, if public, to other scripts. By convention, names that start with an underscore (_speed) are "private": still accessible, but a signal "don't touch this from outside".

Stand-in: types, integer division and formatting in Python

This is not GDScript: Python's // plays the role of GDScript's integer /, and % formatting looks alike. Run it to see the numbers.

Python Stand-in (Python): the same ideas

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

One known difference: Python's round(3.5) is 4 but round(2.5) is 2 (banker's rounding), while GDScript's roundi(2.5) is 3.

Common mistakes

  • Using a variable before declaring it, or declaring the same name twice in one scope.
  • Mixing tabs and spaces.
  • Forgetting that := locks the type: var x := 5 then x = "a" is an error.
  • Integer division where a float is expected (1 / 2 is 0).
  • Comparing floats with ==. Use is_equal_approx(a, b).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does var speed := 200.0 do?

    := infers the type from the value, here float, and locks it.
  2. 2. What is printed by print(7 / 2) when both numbers are int?

    Dividing two ints in GDScript gives an int (integer division), 3.
  3. 3. How do you safely compare two floats?

    Floating-point rounding makes == unreliable; is_equal_approx allows a tiny error.
  4. 4. Which keyword declares something that cannot change?

    const declares a constant. final does not exist in GDScript.

Summary

  • A script is a class: extends names the base node; members use var and const.
  • Add types (var x: int, var x := 5) for earlier errors and speed.
  • Know the built-in types: int, float, String, Vector2, Array, Dictionary, Color, Variant.
  • Integer / truncates; use floats or %/** where needed; compare floats with is_equal_approx.
  • Use % formatting and str() for text.

Next: Control Flow and Functions in GDScript