Function with optional arguments

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By jospic
:warning: Old Version Published before Godot 3 was released.

Hi,
what is the best way to create a GDscript function with a variable number of arguments (some optional)?

Thanks in advance.

-j

The best way to do this, as I see it, is to declare a default value for the parameter:

func _print_name(firstName, middleName, lastName := ""):
	return firstName+middleName+lastName

At this point, you should be able to do something like “_print_name(“Jose”, “Aldo”)” easily.

CaioLuppo | 2022-07-20 15:41

:bust_in_silhouette: Reply From: sleepprogger

As far as i know there are no named parameter in GDScript so you can’t do this like in python:

def foo(a,b=1,c=2):
  ....
foo("first param", c=5)

gdScript supports optional parameter tho.

func foo(a,b=1,c=2):
  ...
    foo("first param", "second param") # the third parameter will have the default value "2"

If you really need the behavior of named parameter i suggest using a dictionary like:

func foo(params={}):
	var a = (1 if not params.has('a') else params['a'])
	var b = (2 if not params.has('b') else params['b'])
	var c = (3 if not params.has('c') else params['c'])
	prints(a, b, c)
foo({a="first param", c="third param"})