Godot 和 GDScript 可以将函数存储在变量中吗?

Can Godot and GDScript store functions in variables?

我对 GDScript language 的部分 Godot 文档感到困惑。大约在页面的中间,在 "Referencing Functions" 部分,它说你不能将函数存储在变量中,然后似乎立即自相矛盾。

Godot函数是否可以存储在变量中?

Referencing Functions

Contrary to Python, functions are not first class objects in GDScript. This means they cannot be stored in variables, passed as an argument to another function or be returned from other functions. This is for performance reasons.

To reference a function by name at runtime, (e.g. to store it in a variable, or pass it to another function as an argument) one must use the call or funcref helpers:

GDScript 函数不像 python 中那样是对象。所以,你不能直接引用一个函数。

但是,您可以使用它们的关联实例按名称间接引用它们。

例如使用以下函数:

func hello():
    print('Hello')

您可以按名称调用实例上的函数:

call('hello') # prints 'Hello'

您可以使用 funcref():

存储实例和函数名称
var ref = funcref(hello_object_instance, 'hello')
ref.call_func() # prints 'Hello'
takes_func_ref_to_call_later(ref) # later, prints 'Hello'

FuncRef.call_func()Object.call() 做同样的事情,只是将它包装在一个对象中。

因此,回调函数的常见模式,如 Object.connect() 和朋友所示,是:

func deferred_finish(param1, param2, callback_obj, callback_func):
    # ... do something
    callback_ref = funcref(callback_obj, callback_func)
func _process(delta):
    if _finished:
        callback_ref.call_func()
func _enter_tree():
    deferred_finish('hello', 'world', self, 'finished_callback')

希望对您有所帮助。如果您需要任何说明,请告诉我。