+15 votes

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

Thanks in advance.


in Engine by (1,486 points)

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 "printname("Jose", "Aldo")" easily.

1 Answer

+23 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 (123 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 Frequently asked questions and 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 [email protected] with your username.