How cool would that be!? Like having multiple constructors for a class or having a move method with the parameters (x:float, y:float) OR (relative:Vector2) ! That'd be super cool and useful I thinks <3

all 2 comments

sorted by: hot top controversial new old
[–] 8 points 2 years ago (1 child)

It's not a thing and I totally agree it should exist, there's a proposal for it on GitHub.

If you want to handle different types, the right way of doing it is giving your parameter a generic type then checking what it is in the function.

func _ready():
    handle_stuff(10)
    handle_stuff("Hello")

func handle_stuff(x: Variant):
    if x is int:
        print("%d is an integer" % x)
    elif x is String:
        print("%s is a string" % x)

This prints 10 is an integer and Hello is a string.

If you really, really need to have a variable amount of arguments in your function, you can pass an array. It's pretty inefficient but you can get away with it.

func handle_stuff(stuff: Array):
    for x: Variant in stuff:
        if x is int:
            print("%d is an integer" % x)
        elif x is String:
            print("%s is a string" % x)

Then you can pass [10, 20, 30] into it or something. It's a useful trick.

  • source
  • hideshow 1 child comment