0 votes

Hello,
Basically I want to do the same thing as how Node.get_node(NodePath path) allows String as an argument.

I want to allow my custom method to take arguments that are different from the expected arguments, but are convertible. (Since method overloading is not supported.)

Ultimately, what I'm hoping to do is, to allow:

Logger.warn("Error loading file!")

# instead of:
#Logger.warn(LogMsg.new("Error loading file!"))

When it's expecting:

# Logger
func warn(m:LogMsg):
    push_warning(m.compose("WARNING"))

# LogMsg
func _init(message:String):
    _message = message

Is there any way this is possible?
Thanks.

Godot version 3.3.2.stable
in Engine by (12 points)

I don't quite follow. The parameter of the custom function needs to be a String or something else? Since GDScript is dynamically typed, any data type supported can be passed to the custom function. So the function can be programmed to behave one way for String input, or it could be programmed to behave for other input.

2 Answers

0 votes

You can allow for any input and check if it's of the right type and do necessary conversion:

func DoSomething(argument):
    if argument is String:
        pass
    elif argument is int:
        pass
    elif argument is Array:
        pass
    else:
        push_error("Argument type is not supported")

Function overloading would be cleaner approach (to get errors on compile time), but currently I think this is the way to do it.

by (382 points)
0 votes

Hello, I found a solution related to your question in the C# language . Here it is https://docs.microsoft.com/en-us/dotnet/api/system.reflection.methodbase.invoke?view=net-5.0

Hope this helps!

Happy Learning!!!

by (18 points)
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.