GDScript reference

GDScript is a high-level, object-oriented, imperative, and gradually typed programming language built for Godot.

GDScript is a high-level, dynamically typed programming language used to create content. It uses an indentation-based syntax similar to languages like Python. Its goal is to be optimized for and tightly integrated with Godot Engine, allowing great flexibility for content creation and integration.

GDScript is entirely independent from Python and is not based on it.

History

Note

Documentation about GDScript's history has been moved to the Frequently Asked Questions.

Example of GDScript

Some people can learn better by taking a look at the syntax, so here's an example of how GDScript looks.

# Everything after "#" is a comment.
# A file is a class!

# (optional) class definition:
class_name MyClass

# Inheritance:
extends BaseClass

# (optional) icon to show in the editor dialogs:
@icon("res://path/to/optional/icon.svg")


# Member variables.
var a = 5
var s = "Hello"
var arr = [1, 2, 3]
var dict = {"key": "value", 2: 3}
var other_dict = {key = "value", other_key = 2}
var typed_var: int
var inferred_type := "String"

# Constants.
const ANSWER = 42
const THE_NAME = "Charly"

# Enums.
enum {UNIT_NEUTRAL, UNIT_ENEMY, UNIT_ALLY}
enum Named {THING_1, THING_2, ANOTHER_THING = -1}

# Built-in vector types.
var v2 = Vector2(1, 2)
var v3 = Vector3(1, 2, 3)


# Functions.
func some_function(param1, param2, param3):
    const local_const = 5

    if param1 < local_const:
        print(param1)
    elif param2 > 5:
        print(param2)
    else:
        print("Fail!")

    for i in range(20):
        print(i)

    while param2 != 0:
        param2 -= 1

    match param3:
        3:
            print("param3 is 3!")
        _:
            print("param3 is not 3!")

    var local_var = param1 + 3
    return local_var


# Functions override functions with the same name on the base/super class.
# If you still want to call them, use "super":
func something(p1, p2):
    super(p1, p2)


# It's also possible to call another function in the super class:
func other_something(p1, p2):
    super.something(p1, p2)


# Inner class
class Something:
    var a = 10


# Constructor
func _init():
    print("Constructed!")
    var lv = Something.new()
    print(lv.a)

If you have previous experience with statically typed languages such as C, C++, or C# but never used a dynamically typed one before, it is advised you read this tutorial: GDScript: An introduction to dynamic languages.

Language

In the following, an overview is given to GDScript. Details, such as which methods are available to arrays or other objects, should be looked up in the linked class descriptions.

Identifiers

Any string that restricts itself to alphabetic characters (a to z and A to Z), digits (0 to 9) and _ qualifies as an identifier. Additionally, identifiers must not begin with a digit. Identifiers are case-sensitive (foo is different from FOO).

Keywords

The following is the list of keywords supported by the language. Since keywords are reserved words (tokens), they can't be used as identifiers. Operators (like in, not, and or or) and names of built-in types as listed in the following sections are also reserved.

Keywords are defined in the GDScript tokenizer in case you want to take a look under the hood.

Keyword

Description

if

See if/else/elif.

elif

See if/else/elif.

else

See if/else/elif.

for

See for.

while

See while.

match

See match.

break

Exits the execution of the current for or while loop.

continue

Immediately skips to the next iteration of the for or while loop. Stops execution in match and looks for a match in patterns below it

pass

Used where a statement is required syntactically but execution of code is undesired, e.g. in empty functions.

return

Returns a value from a function.

class

Defines a class.

class_name

Defines the script as a globally accessible class with the specified name.

extends

Defines what class to extend with the current class.

is

Tests whether a variable extends a given class, or is of a given built-in type.

as

Cast the value to a given type if possible.

self

Refers to current class instance.

signal

Defines a signal.

func

Defines a function.

static

Defines a static function. Static member variables are not allowed.

const

Defines a constant.

enum

Defines an enum.

var

Defines a variable.

breakpoint

Editor helper for debugger breakpoints.

preload

Preloads a class or variable. See Classes as resources.

await

Waits for a signal or a coroutine to finish. See Awaiting for signals.

yield

Previously used for coroutines. Kept as keyword for transition.

assert

Asserts a condition, logs error on failure. Ignored in non-debug builds. See Assert keyword.

void

Used to represent that a function does not return any value.

PI

PI constant.

TAU

TAU constant.

INF

Infinity constant. Used for comparisons and as result of calculations.

NAN

NAN (not a number) constant. Used as impossible result from calculations.

Operators

The following is the list of supported operators and their precedence.

Operator

Description

x[index]

Subscription (highest priority)

x.attribute

Attribute reference

foo()

Function call

is

Instance type checker

**

Power operator

Multiplies value by itself x times, similar to calling pow built-in function

~

Bitwise NOT

-x

Negative / Unary negation

* / %

Multiplication / Division / Remainder

These operators have the same behavior as C++. Integer division is truncated rather than returning a fractional number, and the % operator is only available for ints (fmod for floats), and is additionally used for Format Strings

+

Addition / Concatenation of arrays

-

Subtraction

<< >>

Bit shifting

&

Bitwise AND

^

Bitwise XOR

|

Bitwise OR

< > == != >= <=

Comparisons

in

When used with the if keyword it checks if a value is within a string, list, range, dictionary, or node. When used with the for keyword it is used to iterate though the contents of a string, list, range, dictionary or node.

not

Boolean NOT

and

Boolean AND

or

Boolean OR

if x else

Ternary if/else

as

Type casting

= += -= *= /= %= **= &= |= <<= >>=

Assignment (lowest priority)

Literals

Literal

Type

45

Base 10 integer

0x8f51

Base 16 (hexadecimal) integer

0b101010

Base 2 (binary) integer

3.14, 58.1e-10

Floating-point number (real)

"Hello", "Hi"

Strings

"""Hello"""

Multiline string

&"name"

StringName

^"Node/Label"

NodePath

$NodePath

Shorthand for get_node("NodePath")

Integers and floats can have their numbers separated with _ to make them more readable. The following ways to write numbers are all valid:

12_345_678  # Equal to 12345678.
3.141_592_7  # Equal to 3.1415927.
0x8080_0000_ffff  # Equal to 0x80800000ffff.
0b11_00_11_00  # Equal to 0b11001100.

Annotations

There are some special tokens in GDScript that act like keywords but are not, they are annotations instead. Every annotation start with the @ character and is specified by a name.

Those affect how the script is treated by external tools and usually don't change the behavior.

For instance, you can use it to export a value to the editor:

@export_range(1, 100, 1, "or_greater")
var ranged_var: int = 50

Annotations can be specified one per line or all in the same line. They affect the next statement that isn't an annotation. Annotations can have arguments sent between parentheses and separated by commas.

Both of these are the same:

@onready
@export_node_path(TextEdit, LineEdit)
var input_field

@onready @export_node_path(TextEdit, LineEdit) var input_field

Here's the list of available annotations:

Annotation

Description

@tool

Enable the Tool mode.

@onready

Defer initialization of variable until the node is in the tree. See @onready annotation.

@icon(path)

Set the class icon to show in editor. To be used together with the class_name keyword.

@rpc

RPC modifiers. See high-level multiplayer docs.

@export

@export_enum

@export_file

@export_dir

@export_global_file

@export_global_dir

@export_multiline

@export_placeholder

@export_range

@export_exp_easing

@export_color_no_alpha

@export_node_path

@export_flags

@export_flags_2d_render

@export_flags_2d_physics

@export_flags_3d_render

@export_flags_3d_physics

Export hints for the editor. See GDScript exports.

Comments

Anything from a # to the end of the line is ignored and is considered a comment.

# This is a comment.

Line continuation

A line of code in GDScript can be continued on the next line by using a backslash (\). Add one at the end of a line and the code on the next line will act like it's where the backslash is. Here is an example:

var a = 1 + \
2

A line can be continued multiple times like this:

var a = 1 + \
4 + \
10 + \
4

Built-in types

Built-in types are stack-allocated. They are passed as values. This means a copy is created on each assignment or when passing them as arguments to functions. The only exceptions are Arrays and Dictionaries, which are passed by reference so they are shared. (Packed arrays such as PackedByteArray are still passed as values.)

Basic built-in types

A variable in GDScript can be assigned to several built-in types.

null

null is an empty data type that contains no information and can not be assigned any other value.

bool

Short for "boolean", it can only contain true or false.

int

Short for "integer", it stores whole numbers (positive and negative). It is stored as a 64-bit value, equivalent to "int64_t" in C++.

float

Stores real numbers, including decimals, using floating-point values. It is stored as a 64-bit value, equivalent to "double" in C++. Note: Currently, data structures such as Vector2, Vector3, and PackedFloat32Array store 32-bit single-precision "float" values.

String

A sequence of characters in Unicode format. Strings can contain the following escape sequences:

Escape sequence

Expands to

\n

Newline (line feed)

\t

Horizontal tab character

\r

Carriage return

\a

Alert (beep/bell)

\b

Backspace

\f

Formfeed page break

\v

Vertical tab character

\"

Double quote

\'

Single quote

\\

Backslash

\uXXXX

Unicode codepoint XXXX (hexadecimal, case-insensitive)

Also, using \ followed by a newline inside a string will allow you to continue it in the next line, without inserting a newline character in the string itself.

GDScript also supports