Functions in GDScript

Functions are central in GDScript. We’ll learn about functions with a few different examples.

# Here's a function that takes two integers and returns
# their sum as an integer.
func plus(a: int, b: int) -> int:
    # GDScript doesn't require explicit returns, but we'll
    # use one here for clarity.
    return a + b

# In GDScript, you need to specify the type for each parameter
# separately, even if they're the same type.
func plus_plus(a: int, b: int, c: int) -> int:
    return a + b + c

# The main function in GDScript is typically the _ready() function
# which is called when the script is loaded.
func _ready():
    # Call a function just as you'd expect, with
    # name(args).
    var res = plus(1, 2)
    print("1+2 =", res)

    res = plus_plus(1, 2, 3)
    print("1+2+3 =", res)

To run this script in Godot:

  1. Attach this script to a Node in your Godot scene.
  2. Run the scene.
  3. The output will be visible in the Output panel:
1+2 = 3
1+2+3 = 6

There are several other features to GDScript functions. One is multiple return values, which we’ll look at next.