如何在 GDScript 中指定任何/未知/变体类型?
有没有办法在 GDScript 中指定未知类型?
GDScript 文档为此使用类型 Variant
(例如在 Array.count 方法)。
比如说,我想写一个恒等函数。我可以这样做:
func identity(x):
return x
但我想声明参数类型和返回值都可以是任何东西。比如:
func identity(x: Variant) -> Variant:
return x
但这不起作用。 Variant
不是已知的类型名称。我尝试了各种名称,机器人似乎不起作用。
放弃类型是唯一的选择吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,唯一的选择是不指定类型。
此函数:
接受
Variant
并返回Variant
。C++ 中的 Godot 中定义了一个
Variant
类。正如您所发现的,我们不能在 GDScript 中按名称使用它。请注意,文档使用基于 C++ 的表示法。例如,
int count (Variant value)
不仅因为Variant
而与 GDScript 不同,而且还在于您在参数后面而不是名称之前指定类型,您也可以在参数后面指定类型。使用func
。这是
int count (Variant value)
在 GDScript 中的样子:func count(value) -> int:
,这是 C++ 定义:int Array::count(const Variant &p_value) const
(源)。 将 C++ 定义与文档中的定义进行比较。再举一个例子,
Array duplicated (bool deep=false)
在 GDSCript 中的样子如下:func副本(深:布尔=假)->数组:
,这是 C++ 定义:Array Array::duplicate(bool p_deep) const
。 (来源)。 请注意,C++ 定义并不表明参数是可选的,而是为脚本绑定添加了信息。Yes, the only option is to not specify the type.
This function:
Takes
Variant
and returnsVariant
.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 ofVariant
, but also in that you specify the type after the parameters not before the name, also you usefunc
.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.