+9 votes

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

Thanks in advance.


asked Oct 31, 2016 in Engine by jospic (1,438 points)

1 Answer

+15 votes
Best answer

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"})
answered Oct 31, 2016 by sleepprogger (116 points)
selected Oct 31, 2016 by jospic
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.