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.



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:

# 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 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:
    elif param2 > 5:

    for i in range(20):

    while param2 != 0:
        param2 -= 1

    match param3:
            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():
    var lv =

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.


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.


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).


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.




See if/else/elif.


See if/else/elif.


See if/else/elif.


See for.


See while.


See match.


Exits the execution of the current for or while loop.


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


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


Returns a value from a function.


Defines a class.


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


Defines what class to extend with the current class.


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


Cast the value to a given type if possible.


Refers to current class instance.


Defines a signal.


Defines a function.


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


Defines a constant.


Defines an enum.


Defines a variable.


Editor helper for debugger breakpoints.


Preloads a class or variable. See Classes as resources.


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


Previously used for coroutines. Kept as keyword for transition.


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


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


PI constant.


TAU constant.


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


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


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




Subscription (highest priority)


Attribute reference


Function call


Instance type checker


Power operator

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


Bitwise NOT


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



<< >>

Bit shifting


Bitwise AND


Bitwise XOR


Bitwise OR

< > == != >= <=



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.


Boolean NOT


Boolean AND


Boolean OR

if x else

Ternary if/else


Type casting

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

Assignment (lowest priority)





Base 10 integer


Base 16 (hexadecimal) integer


Base 2 (binary) integer

3.14, 58.1e-10

Floating-point number (real)

"Hello", "Hi"



Multiline string






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.


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:

@export_node_path(TextEdit, LineEdit)
var input_field

@onready @export_node_path(TextEdit, LineEdit) var input_field

Here's the list of available annotations:




Enable the Tool mode.


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


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


RPC modifiers. See high-level multiplayer docs.


















Export hints for the editor. See GDScript exports.


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 + \

A line can be continued multiple times like this:

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

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 is an empty data type that contains no information and can not be assigned any other value.


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


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


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.


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

Escape sequence

Expands to


Newline (line feed)


Horizontal tab character


Carriage return


Alert (beep/bell)




Formfeed page break


Vertical tab character


Double quote


Single quote




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 GDScript format strings.


An immutable string that allows only one instance of each name. They are slower to create and may result in waiting for locks when multithreading. In exchange, they're very fast to compare, which makes them good candidates for dictionary keys.


A pre-parsed path to a node or a node property. They are useful to interact with the tree to get a node, or affecting properties like with Tweens.

Vector built-in types


2D vector type containing x and y fields. Can also be accessed as an array.


Same as a Vector2 but the components are integers. Useful for representing items in a 2D grid.


2D Rectangle type containing two vectors fields: position and size. Also contains an end field which is position + size.


3D vector type containing x, y and z fields. This can also be accessed as an array.


Same as Vector3 but the components are integers. Can be use for indexing items in a 3D grid.


3×2 matrix used for 2D transforms.


3D Plane type in normalized form that contains a normal vector field and a d scalar distance.


Quaternion is a datatype used for representing a 3D rotation. It's useful for interpolating rotations.


Axis-aligned bounding box (or 3D box) contains 2 vectors fields: position and size. Also contains an end field which is position + size.


3x3 matrix used for 3D rotation and scale. It contains 3 vector fields (x, y and z) and can also be accessed as an array of 3D vectors.


3D Transform contains a Basis field basis and a Vector3 field origin.

Engine built-in types


Color data type contains r, g, b, and a fields. It can also be accessed as h, s, and v for hue/saturation/value.


Compiled path to a node used mainly in the scene system. It can be easily assigned to, and from, a String.


Resource ID (RID). Servers use generic RIDs to reference opaque data.


Base class for anything that is not a built-in type.

Container built-in types


Generic sequence of arbitrary object types, including other arrays or dictionaries (see below). The array can resize dynamically. Arrays are indexed starting from index 0. Negative indices count from the end.

var arr = []
arr = [1, 2, 3]
var b = arr[1] # This is 2.
var c = arr[arr.size() - 1] # This is 3.
var d = arr[-1] # Same as the previous line, but shorter.
arr[0] = "Hi!" # Replacing value 1 with "Hi!".
arr.append(4) # Array is now ["Hi!", 2, 3, 4].

GDScript arrays are allocated linearly in memory for speed. Large arrays (more than tens of thousands of elements) may however cause memory fragmentation. If this is a concern, special types of arrays are available. These only accept a single data type. They avoid memory fragmentation and use less memory, but are atomic and tend to run slower than generic arrays. They are therefore only recommended to use for large data sets:


Associative container which contains values referenced by unique keys.

var d = {4: 5, "A key": "A value", 28: [1, 2, 3]}
d["Hi!"] = 0
d = {
    22: "value",
    "some_key": 2,
    "other_key": [2, 3, 4],
    "more_key": "Hello"

Lua-style table syntax is also supported. Lua-style uses = instead of : and doesn't use quotes to mark string keys (making for slightly less to write). However, keys written in this form can't start with a digit (like any GDScript identifier).

var d = {
    test22 = "value",
    some_key = 2,
    other_key = [2, 3, 4],
    more_key = "Hello"

To add a key to an existing dictionary, access it like an existing key and assign to it:

var d = {} # Create an empty Dictionary.
d.waiting = 14 # Add String "waiting" as a key and assign the value 14 to it.
d[4] = "hello" # Add integer 4 as a key and assign the String "hello" as its value.
d["Godot"] = 3.01 # Add String "Godot" as a key and assign the value 3.01 to it.

var test = 4
# Prints "hello" by indexing the dictionary with a dynamic key.
# This is not the same as `d.test`. The bracket syntax equivalent to
# `d.test` is `d["test"]`.


The bracket syntax can be used to access properties of any Object, not just Dictionaries. Keep in mind it will cause a script error when attempting to index a non-existing property. To avoid this, use the Object.get() and Object.set() methods instead.


A signal is a message that can be emitted by an object to those who want to listen to it. The Signal type can be used for passing the emitter around.

Signals are better used by getting them from actual objects, e.g. $Button.button_up.


Contains an object and a function, which is useful for passing functions as values (e.g. when connecting to signals).

Getting a method as a member returns a callable. var x = $Sprite2D.rotate will set the value of x to a callable with $Sprite2D as the object and rotate as the method.

You can call it using the call method:



Variables can exist as class members or local to functions. They are created with the var keyword and may, optionally, be assigned a value upon initialization.

var a # Data type is 'null' by default.
var b = 5
var c = 3.8
var d = b + c # Variables are always initialized in order.

Variables can optionally have a type specification. When a type is specified, the variable will be forced to have always that same type, and trying to assign an incompatible value will raise an error.

Types are specified in the variable declaration using a : (colon) symbol after the variable name, followed by the type.

var my_vector2: Vector2
var my_node: Node =

If the variable is initialized within the declaration, the type can be inferred, so it's possible to omit the type name:

var my_vector2 := Vector2() # 'my_vector2' is of type 'Vector2'.
var my_node := # 'my_node' is of type 'Sprite2D'.

Type inference is only possible if the assigned value has a defined type, otherwise it will raise an error.

Valid types are:

  • Built-in types (Array, Vector2, int, String, etc.).

  • Engine classes (Node, Resource, Reference, etc.).

  • Constant names if they contain a script resource (MyScript if you declared const MyScript = preload("res://")).

  • Other classes in the same script, respecting scope (InnerClass.NestedClass if you declared class NestedClass inside the class InnerClass in the same scope).

  • Script classes declared with the class_name keyword.

  • Autoloads registered as singletons.


Values assigned to typed variables must have a compatible type. If it's needed to coerce a value to be of a certain type, in particular for object types, you can use the casting operator as.

Casting between object types results in the same object if the value is of the same type or a subtype of the cast type.

var my_node2D: Node2D
my_node2D = $Sprite2D as Node2D # Works since Sprite2D is a subtype of Node2D.

If the value is not a subtype, the casting operation will result in a null value.

var my_node2D: Node2D
my_node2D = $Button as Node2D # Results in 'null' since a Button is not a subtype of Node2D.

For built-in types, they will be forcibly converted if possible, otherwise the engine will raise an error.

var my_int: int
my_int = "123" as int # The string can be converted to int.
my_int = Vector2() as int # A Vector2 can't be converted to int, this will cause an error.

Casting is also useful to have better type-safe variables when interacting with the scene tree:

# Will infer the variable to be of type Sprite2D.
var my_sprite := $Character as Sprite2D

# Will fail if $AnimPlayer is not an AnimationPlayer, even if it has the method 'play()'.
($AnimPlayer as AnimationPlayer).play("walk")


Constants are values you cannot change when the game is running. Their value must be known at compile-time. Using the const keyword allows you to give a constant value a name. Trying to assign a value to a constant after it's declared will give you an error.

We recommend using constants whenever a value is not meant to change.

const A = 5
const B = Vector2(20, 20)
const C = 10 + 20 # Constant expression.
const D =