Reputation: 13917
Is there a way to specify an unknown type in GDScript?
GDScript docs use the type Variant
for this (for example in Array.count method).
Say, I'd like to write an identity function. I can do it like so:
func identity(x):
return x
But I'd like to declare that both the parameter type and return value could be anything. Something like:
func identity(x: Variant) -> Variant:
return x
This doesn't work though. Variant
is not a known type name. I tried various names, bot nothing seems to work.
Is the only option to leave off the type?
Upvotes: 1
Views: 2039
Reputation: 40305
Yes, the only option is to not specify the type.
This function:
func identity(x):
return x
Takes Variant
and returns Variant
.
There is a Variant
class defined in Godot in C++. Which, as you have found out, we cannot use it by name in GDScript.
Please notice that the docs use a notation based on C++. For instance int count (Variant value)
does not only differ from GDScript because of Variant
, but also in that you specify the type after the parameters not before the name, also you use func
.
This is how int count (Variant value)
looks in GDScript: func count(value) -> int:
, and this is the C++ definition: int Array::count(const Variant &p_value) const
(source). Compare the C++ definition with the one on the documentation.
For another example, this is how Array duplicate (bool deep=false)
looks like in GDSCript: func duplicate(deep:bool=false) -> Array:
, and this is the C++ definition: Array Array::duplicate(bool p_deep) const
. (source). Notice the C++ definition does not indicate the parameter will be optional, that information is added for the script binding.
Upvotes: 2