此代码将引发一个解析错误:
func foo():
func bar():
pass
pass
Error pasing expression, misplaced: func
是否有特殊的关键字或其他技巧来定义内部函数?
发布于 2021-05-03 12:53:00
不是在戈多3.x。Godot4.0用给定的语法支持这一点。这是提议:“在GDScript中添加lambda函数”。
增编:我应该指出,惯例是,任何带有下划线("_")的星星都应该被视为私有的。而从外部访问它们则是你自己的风险。这种方法已经在Python上运行了很长一段时间。
有些事情你可以做,…
“私人”领域
正如您所知道的,您可以使用setget
让getter和setter在每次您访问外部字段时运行,或者使用self
。好吧,你可以写那些失败的setter和setter。
例如:
var _value setget noset, noget
func noset(_new_value):
push_error("Invalid access.")
func noget():
push_error("Invalid access.")
这将导致从另一个脚本中使用错误。如果使用self._value
从相同的脚本中使用,但不使用来自同一个脚本的_value
(不使用self),也会导致错误。因此,我们有一个“私人”领域。
类似地,仅通过指定setter,我们可以拥有一个只读属性:
var value setget noset
func noset(_new_value):
push_error("Invalid access.")
“私”法
按照同样的想法,我们可以将令牌存储在私有字段中。然后用它作为访问检查。我们将使用一个新的对象,使它是不可能匹配的偶然。这类似于拥有一个监视器(如线程中所理解的)、持有锁和执行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
是“私有”的,传递其他任何内容都会导致错误。因此,不可能从另一个脚本中使用该方法。
这是https://github.com/godotengine/godot-proposals/issues/641#issuecomment-699579606的一个改进版本。关于https://github.com/godotengine/godot-proposals/issues/641的提案。
评估代码
您可以做的其他事情是从代码中创建一个脚本(比如"eval")。这是通过GDScript
类完成的。
您可以像这样创建脚本:
var script = GDScript.new()
script.source_code = "func run():print('hello world')" # create code at runtime
script.reload()
实例化如下:
var script_instance = script.new()
当然,您可以将实例保存在“私有”字段中。您也可能对https://docs.godotengine.org/en/stable/classes/class_funcref.html感兴趣。
然后使用您在其中声明的任何内容,在本例中使用run
函数:
script_instance.call("run")
如果不在运行时创建代码,则可以使用load
加载脚本。或者使用内部类。
如果不需要完整的脚本,则可以使用Expression
。
https://stackoverflow.com/questions/67374441
复制相似问题