+1 vote
func is_type(res, type) -> bool:
    return res is type

The function works fine but I always use static typing when possible and I can't figure out what the type parameter static type should be.

Variant or Type is not posible so I tried type: Reference and type: Object but I get:

error(45, 1): Invalid "is" test: the right operand isn't a type(neither a native type nor a script).

In C# you can use Type or a generic, It's not big deal but I kinda wanna know if it's posible in GDscript

Godot version 3.2.3
in Engine by (164 points)

2 Answers

0 votes

It is GDScriptNativeClass.However, the compiler doesn't seem to like it, so you could use a type := Node instead.

You had your error because type could not be converted to Object or Reference, and was therefore replaced with null.

by (2,720 points)
+1 vote

is is a kind of macro and can't take right variable arguments.
Also, there are no available GDScriptNativeClass methods to do some instrospection like getting class name of a GDScriptNativeClass var like in following, that you would pass as argument to your is_type function

var a_type = SpatialMaterial

But that would be rewriting is, itself anyway.

Without more context, something like this could do the job as, i suppose, you want to store types somewhere

func _ready():
    var foo = SpatialMaterial.new()
    print(is_type(foo, "SpatialMaterial"))
    print(is_type(ColorN("red", 1), TYPE_COLOR))

func is_type(res, type) -> bool:
    if type is String:
        return res is Object and res.get_class() == type
    return typeof(res) == type
by (340 points)

I just made up the function to know if it was possible, my actual use case is a function that fetches all resources in a folder, so I need a "type" to define what resources I want

"type" or descriptors of types are strings
see also eventually https://docs.godotengine.org/en/stable/development/file_formats/tscn.html#resources

as said, currently, you just can't use is function directly in its current form.
if you aren't testing against primitive types, you may use, something like

func is_type(res, type) -> bool:
        return res is Object and res.get_class() == type
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.