+12 votes

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

Thanks in advance.

-j

in Engine by (1,464 points)

1 Answer

+18 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"})
by (118 points)
selected by
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.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.