GDScript

GDScript Cheat Sheet

GDScript is a high-level, both static and dynamically typed programming language specifically designed for the Godot game engine.

Basic Syntax

Operators

Arithmetic

  • Addition: a + b
  • Subtraction: a - b
  • Multiplication: a * b
  • Division: a / b
  • Modulus: a % b
  • Power: a ** b

Comparison

  • Equal: a == b
  • Not equal: a != b
  • Less than: a < b
  • Less than or equal: a <= b
  • Greater than: a > b
  • Greater than or equal: a >= b

Logical

  • And: a and b or a && b
  • Or: a or b or a || b
  • Not: not a or !a

Bitwise

  • Bitwise AND: a & b
  • Bitwise OR: a | b
  • Bitwise XOR: a ^ b
  • Bitwise NOT: ~a
  • Left shift: a << b
  • Right shift: a >> b

Assignment

  • Assign: a = b
  • Add and assign: a += b
  • Subtract and assign: a -= b
  • Multiply and assign: a *= b
  • Divide and assign: a /= b
  • Modulus and assign: a %= b
  • Power and assign: a **= b
  • Left shift and assign: a <<= b
  • Right shift and assign: a >>= b
  • Bitwise AND and assign: a &= b
  • Bitwise OR and assign: a |= b
  • Bitwise XOR and assign: a ^= b

Constants

  • Declare a constant: const MY_CONSTANT = 100

Static Variables

Static variables belong to a class rather than an instance of the class. To define a static variable, use the static keyword:

  • Declare a static variable: static var my_static_variable = 30
  • Change the value of a static variable: my_static_variable = 40
  • Since statics belong to the class, you can also use MyClass.my_static_variable = 40

Arrays and Dictionaries

GDScript also provides built-in data structures like arrays and dictionaries:

  • Array: Ordered list of elements
  • Dictionary: Key-value pairs

Variables

In GDScript, variables can be declared using the var keyword.

  • Declare a variable: var my_variable = 10
  • Change the value of a variable: my_variable = 20
  • Declare a variable with a specific type: var my_int: int = 5

Here are some common data types in GDScript:

  • int: Integer numbers
  • float: Floating-point numbers
  • bool: Boolean values (true or false)
  • String: Text strings

Indentation

GDScript uses indentation to define code blocks, just like Python:

func _init():
    pass

Basic Output

To print output in GDScript, use the print() function:

print("Hello, Godot!")

Comments

Single-line comments:

# This is a single-line comment

Multi-line comments

"""
This is a multiline string, not a comment!
And thus it will be parsed by interpreter...
"""

# Now this
# is a multiline comments
# Interpreter will not read this

Variable Typing

Static Typing

var my_int: int = 5
my_int = "Hello, GDScript!" # This will cause an error

Dynamic Typing

var my_variable = 10
my_variable = "Hello, GDScript!" # This is allowed

Control Structures

Loops

The for loop is used to iterate over a sequence, such as an array or a range of numbers:

for i in range(5):
    print(i) # Prints 0, 1, 2, 3, 4

for item in my_array:
    print(item) # Prints each item in my_array

The while loop is used to repeatedly execute a block of code as long as a certain condition is true:

var i = 0
while i < 5:
    print(i) # Prints 0, 1, 2, 3, 4
    i += 1

The break statement is used to exit a loop prematurely:

for i in range(10):
    if i == 5:
        break
    print(i) # Prints 0, 1, 2, 3, 4

The continue statement is used to skip the rest of the current iteration and proceed to the next one:

for i in range(5):
    if i == 2:
        continue
    print(i) # Prints 0, 1, 3, 4

Conditional statements

The if statement is used to execute a block of code if a certain condition is true:

if x > 0:
    print("x is positive")

The else statement is used to execute a block of code if the condition in the if statement is false:

if x > 0:
    print("x is positive")
else:
    print("x is not positive")

The elif (short for "else if") statement is used to test multiple conditions in a single if statement:

if x > 0:
    print("x is positive")
elif x < 0:
    print("x is negative")
else:
    print("x is zero")

Functions

Static Functions

Static functions are functions that belong to a class rather than an instance of the class. To define a static function, use the static keyword:

class_name  MyClass extends Node

static func my_static_function():
    print("This is a static function.")

func _init() -> void:
    my_static_function()
    MyClass.my_static_function()

Optional argument values

Functions can have an optional argument as value by assigning it at the definition:

func multiply(a: int, b: int = 2) -> int:
    return a * b

var result = multiply(2, 3) # result is 6
var result = multiply(4) # result is 8

Return values

Functions can return a result using the return keyword:

func add(a, b):
    return a + b

var result = add(2, 3) # result is 5

You can also define the type of the returned value by appending -> ReturnType to the function declaration, it will spit out an error if you try to return something that isn't the correct type.

# Returns integer
func add(a: int, b: int) -> int:
    return a + b

# This won't work
func add(a, b) -> int:
    return "Hello"

Function arguments

To define a function with arguments, include the argument names inside the parentheses:

func add(a, b):
    return a + b

You can also define the types of the arguments.

func add(a: int, b: int):
    return a + b

Built-in functions

Some examples include:

  • print(): Prints a message to the console
  • randi(): Returns a random integer
  • len(): Returns the length of a sequence (e.g., an array or a string)

Defining functions

func my_function():
    print("Hello, GDScript!")

Classes and Objects

Constructors

Constructors are special methods that are called when an object is initialized. In GDScript, the constructor is named _init:

class MyClass:
    func _init():
        print("Object initialized!")

Inheritance

Inheritance is a way for one class to inherit the properties and methods of another class. To inherit from another class, use the extends keyword:

# Derived class
class_name DerivedClass extends MyBaseClass

func my_method():
    print("Hello from the derived class!")

Methods

Methods are functions that belong to a class or an object. They can be used to perform actions or manipulate data:

class MyClass:
    func my_method():
        print("Hello, GDScript!")

Properties

Properties are variables that belong to a class or an object. They can be used to store data or state:

class MyClass:
    var my_property = 0

Creating Object

var player = Player.new()
player.name = "John Doe"
player.take_damage(50)

Defining Classes

To define a class, simply create a new script file (e.g., my_class.gd). The name of the file should represents the name of the class. Create a new file called player.gd with the following content:

class_name Player

var health: int = 100
var name: String = "Unnamed"

func take_damage(amount: int):
    health -= amount
    if health <= 0:
        print("Player", name, "has died!")

Signals and Events

Connecting signals to functions

To connect a signal to a function, use the connect method:

my_object.my_signal.connect(on_my_signal)

func on_my_signal():
    print("Signal received!")

Emitting signals

To emit a signal, you can use the emit_signal method:

emit_signal("my_signal")

However, it's better to ditch those strings, by simply calling emit method inside the signal directly:

my_signal.emit()

Defining signals

To define a signal, use the signal keyword followed by the signal name:

signal my_signal

Error Handling

Try, Catch, and Throw

GDScript does not have built-in support for try-catch blocks. There are many godot-proposals from people asking for it, however, It has already been stated that try-catch will never come into gdscript.

Assert

The assert statement is used to check if a condition is true, and if not, raise an error:

assert(x > 0, "x must be positive")

File I/O

Closing files

To close a file, use the close method:

file.close()

Reading and writing

To read from a file, use the get_as_text or other get_* method:

var file = FileAccess.open("user://save_game.dat", FileAccess.READ)
var player_name = file.get_as_text()
print(player_name)

Writing a file

To write to a file, use the store_string, store_line or other store_* methods:

var player_name = "Septian"
var file = FileAccess.open("user://save_game.dat", FileAccess.WRITE)
file.store_string(player_name)

Useful Tips and Tricks

Debugging

  • Print a message to the console: print("Hello, GDScript!")
  • Set a breakpoint: breakpoint

Type casting

  • Cast a value to a specific type: var my_int = int("42")

Array and Dictionary operations

  • Add an item to an array: my_array.append(item)
  • Remove an item from an array: my_array.erase(item)
  • Get the length of an array: var length = my_array.size()
  • Check if a key exists in a dictionary: if my_dict.has(key):

String manipulation

  • String interpolation:
var result = "The %s has defeated the %s in %s" % ["Player", "Boss", "Combat"]
print(result)
# Will prints:
# The Player has defeated the Boss in Combat
  • Concatenate strings: var result = "Hello, " + "GDScript!"
  • Format strings: var result = "Hello, %s!" % "GDScript"
  • Split strings: var words = "Hello, GDScript!".split(", ")