有没有办法在另一个函数中定义一个辅助函数?

Is there a way to define an helper function inside another one?

此代码引发解析错误:

func foo():
 func bar():
   pass
 pass

Error pasing expression, misplaced: func


是否有特殊的关键字或其他技巧来定义内部函数?

不在 Godot 3.x。这在 Godot 4.0 中受支持,具有给定的语法。这是提案:"Add lambda functions in GDScript".

附录:我应该提一下,惯例是任何带有下划线(“_”)的星星都被认为是私人的。从外部访问它们的风险由您自行承担。 这种方法在 Python 很长一段时间内效果很好

有些事情你可以做...


“私人”字段

如您所知,您可以使用 setget 获取吸气剂和 setters 每次您从外部访问字段或使用 self 时都会 运行 .好吧,你可以写 getters 和 setter 只是失败。

例如:

var _value setget noset, noget

func noset(_new_value):
    push_error("Invalid access.")

func noget():
    push_error("Invalid access.")

这在从另一个脚本使用时会导致错误。当从具有 self._value 的同一脚本使用时也会导致错误,但不从同一脚本(没有 self)使用 _value。因此我们有一个“私有”字段。

同样,通过只指定 setter,我们可以有一个只读的 属性:

var value setget noset

func noset(_new_value):
    push_error("Invalid access.")

“私有”方法

按照同样的思路,我们可以在私有字段中存储一个token。并将其用作访问检查。我们将使用一个新对象,这样就不可能偶然匹配到它。 这类似于拥有监视器(在线程中理解)、持有锁并执行 try_enter… 除了没有线程部分。

var _token setget noset, noget

func noset(_new_value):
    push_error("Invalid access.")

func noget():
    push_error("Invalid access.")

func _method(token):
    if token != _token: # try enter
        push_error("Invalid access") # did fail to enter
        return

    # did enter
    pass

func _init():
    _token = ClassDB.instance("Object") # hold lock

从同一个脚本,您可以访问 _token。因此,您可以这样调用该方法:

_method(_token)

但是,_token 是“私有的”,传递任何其他内容都会导致错误。因此,将无法使用其他脚本中的方法。

这是a comment by me2beats. On the proposal "Add public/private access modifiers to GDScript and autocompletion improvements"的改进版本。


评估代码

您可以做的其他事情是从代码中创建一个脚本(想想“eval”)。这是通过 GDScript class.

完成的

您可以这样创建脚本:

var script = GDScript.new()
script.source_code = "func run():print('hello world')" # create code at runtime
script.reload()

像这样实例化它:

var script_instance = script.new()

当然,您可以将实例保存在“私有”字段中。您可能还对 FuncRef.

感兴趣

然后使用您在其中声明的任何内容,在本例中为 run 函数:

script_instance.call("run")

参见 call, get, set


如果您不在 运行 时创建代码,则可以使用 load 加载脚本。或者使用 Inner class.

如果您不需要整个脚本,您可以使用 Expression