Attention: Here be dragons
This is the latest
(unstable) version of this documentation, which may document features
not available in or compatible with released stable versions of Godot.
Checking the stable version of the documentation...
Expression
继承: RefCounted < Object
存储你可以执行的表达式的类。
描述
表达式可以由任何算术运算、内置数学函数调用、传递实例的方法调用或内置类型构造调用组成。
一个使用内置数学函数的示例表达式文本可以是 sqrt(pow(3, 2) + pow(4, 2))
。
在下面的示例中,我们使用 LineEdit 节点来编写表达式并显示结果。
var expression = Expression.new()
func _ready():
$LineEdit.text_submitted.connect(self._on_text_submitted)
func _on_text_submitted(command):
var error = expression.parse(command)
if error != OK:
print(expression.get_error_text())
return
var result = expression.execute()
if not expression.has_execute_failed():
$LineEdit.text = str(result)
private Expression _expression = new Expression();
public override void _Ready()
{
GetNode<LineEdit>("LineEdit").TextSubmitted += OnTextEntered;
}
private void OnTextEntered(string command)
{
Error error = _expression.Parse(command);
if (error != Error.Ok)
{
GD.Print(_expression.GetErrorText());
return;
}
Variant result = _expression.Execute();
if (!_expression.HasExecuteFailed())
{
GetNode<LineEdit>("LineEdit").Text = result.ToString();
}
}
教程
方法
execute(inputs: Array = [], base_instance: Object = null, show_error: bool = true, const_calls_only: bool = false) |
|
get_error_text() const |
|
has_execute_failed() const |
|
parse(expression: String, input_names: PackedStringArray = PackedStringArray()) |
方法说明
Variant execute(inputs: Array = [], base_instance: Object = null, show_error: bool = true, const_calls_only: bool = false) 🔗
执行之前由 parse() 解析的表达式,并返回结果。在使用返回的对象之前,应该通过调用 has_execute_failed() 来检查方法是否失败。
如果你在 parse() 中定义了输入变量,你可以在输入数组中以同样的顺序指定它们的值。
String get_error_text() const 🔗
如果 parse() 或 execute() 失败,则返回错误文本。
bool has_execute_failed() const 🔗
如果 execute() 失败,返回 true
。
Error parse(expression: String, input_names: PackedStringArray = PackedStringArray()) 🔗
解析表达式并返回 Error 代码。
你也可以选择用 input_names
来指定可能出现在表达式中的变量名称,这样就可以在执行表达式时进行绑定。