如何在 GDScript 中指定任何/未知/变体类型?

发布于 2025-01-09 01:36:46 字数 513 浏览 1 评论 0原文

有没有办法在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

意中人 2025-01-16 01:36:46

是的,唯一的选择是不指定类型。

此函数:

func identity(x):
    return x

接受 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:

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文