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!")
Comments