Variadic Functions in GDScript

Here’s the full source code to demonstrate how variadic functions work.

extends Node

func sum(nums : Array) -> void:
    # Prints the array for debugging
    print(nums, " ")
    var total := 0

    for num in nums:
        total += int(num)
    print(total)

func _ready():
    # Variadic functions can be called in the usual way with individual arguments.
    sum([1, 2])
    sum([1, 2, 3])

    # If you already have multiple args in an array, apply them to a variadic function using func(arr) like this.
    var nums = [1, 2, 3, 4]
    sum(nums)

To run this script, save it in a file (e.g., variadic_functions.gd) and attach it to a Node in your Godot project.

$ godot --path /path/to/your/project -s variadic_functions.gd

This will output:

[1, 2] 3
[1, 2, 3] 6
[1, 2, 3, 4] 10

Godot provides an easy way to demonstrate variadic functions using arrays. Now that we can run and understand how variadic functions work in Godot, let’s learn more about the language.

查看推荐产品