How can I set a default for an argument?

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

I want to print “Hello” if I don’t set an argument. And how is it possible functions not to have necessarily an argument/all possible agruments so it would be ignored then?

extends Node

func _on_Button_pressed():

func say_something(string)
:bust_in_silhouette: Reply From: jgodfrey

You can specify default values for arguments like:

func say_something(string = "Hello"):

With that…

say() # will print "Hello"
say("Bye") # will print "Bye"

Thank you very much!

MaaaxiKing | 2020-05-20 20:12

Is it a bug if this doesn’t work: func say_something(string:String="Hello",a)
Seems that if you have set a default to a paramater before another parameter without a default, you have to set a default to the parameter after the first parameter which has a default.
Error message: Default parameter expected.
func say_something(a,string:String="Hello") works

MaaaxiKing | 2020-05-20 20:33

No, that’s not a bug. Arguments with default values must be at the end of the function’s argument list. That’s a fairly common restriction in a number of languages.

jgodfrey | 2020-05-20 22:09