Is variable arguments supported in gdscript?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By alexzheng

I want to define a method with variable arguments, is that supported?

:bust_in_silhouette: Reply From: Zaven Muradyan

Unfortunately, it doesn’t appear that this is supported yet: GDScript: Variadic functions (variable number of arguments/varargs) · Issue #16565 · godotengine/godot · GitHub

The basic workaround would be to accept an array argument and just use array notation at the call site:

func foo(args):
    for x in args:
foo(["hello", "world"])
:bust_in_silhouette: Reply From: jagc

This is a duplicate of this question.
The answer provided there hits it perfectly.

For those too lazy to click the link, this is one example variation of implementing the answer:

func nameOfFunc(firstArg, params = {}):
  var data = firstArg

  # Ternary operation just to keep it short
  # But you can do whatever you want when:
  #   checking a key's existence and assigning values
  var a = (0 if not params.has('a') else params['a'])
  var b = (0 if not params.has('b') else params['b'])
  var c = (0 if not params.has('c') else params['c'])

  data += a + b + c

  return data

So let’s call it inside a function.

func printExample():
  var a = 1
  var c = 1

  # in our definition, we have named optional parameters 'a', 'b', 'c'
  # we're only setting up to use 'a' and 'c'
  var params = {
    a = a,
    c = c

  var sum = nameOfFunc(1, params)

  print(sum) # output: 3

Tested working at Godot 3.1.1

Old thread, but in case someone else stumbles on this like I did, I want to add two points:

  1. Since dictionaries are mutable, using them as a default param value is dangerous. Any changes to the params dict in the method would persist across method calls, causing unwanted behavior.
  2. You can simplify the code for getting the params by using dictionary’s built-in .get() method instead of using inline if statements.

With the above two considerations, here’s what I’d do for arbitrary parameters:

func nameOfFunc(firstArg, params = null):
var data = firstArg

if params != null:
    var a = params.get('a', 0)
    var b = params.get('b', 0)
    var c = params.get('c', 0)
    data += a + b + c
return data

BigOzzie | 2022-10-02 17:53