Up to date

This page is up to date for Godot 4.1. If you still find outdated information, please open an issue.

Expression

Inherits: RefCounted < Object

A class that stores an expression you can execute.

Description

An expression can be made of any arithmetic operation, built-in math function call, method call of a passed instance, or built-in type construction call.

An example expression text using the built-in math functions could be sqrt(pow(3, 2) + pow(4, 2)).

In the following example we use a LineEdit node to write our expression and show the result.

GDScriptC#

  1. var expression = Expression.new()
  2. func _ready():
  3. $LineEdit.text_submitted.connect(self._on_text_submitted)
  4. func _on_text_submitted(command):
  5. var error = expression.parse(command)
  6. if error != OK:
  7. print(expression.get_error_text())
  8. return
  9. var result = expression.execute()
  10. if not expression.has_execute_failed():
  11. $LineEdit.text = str(result)
  1. private Expression _expression = new Expression();
  2. public override void _Ready()
  3. {
  4. GetNode<LineEdit>("LineEdit").TextSubmitted += OnTextEntered;
  5. }
  6. private void OnTextEntered(string command)
  7. {
  8. Error error = _expression.Parse(command);
  9. if (error != Error.Ok)
  10. {
  11. GD.Print(_expression.GetErrorText());
  12. return;
  13. }
  14. Variant result = _expression.Execute();
  15. if (!_expression.HasExecuteFailed())
  16. {
  17. GetNode<LineEdit>("LineEdit").Text = result.ToString();
  18. }
  19. }

Tutorials

Methods

Variant

execute ( Array inputs=[], Object base_instance=null, bool show_error=true, bool const_calls_only=false )

String

get_error_text ( ) const

bool

has_execute_failed ( ) const

Error

parse ( String expression, PackedStringArray input_names=PackedStringArray() )


Method Descriptions

Variant execute ( Array inputs=[], Object base_instance=null, bool show_error=true, bool const_calls_only=false )

Executes the expression that was previously parsed by parse and returns the result. Before you use the returned object, you should check if the method failed by calling has_execute_failed.

If you defined input variables in parse, you can specify their values in the inputs array, in the same order.


String get_error_text ( ) const

Returns the error text if parse or execute has failed.


bool has_execute_failed ( ) const

Returns true if execute has failed.


Error parse ( String expression, PackedStringArray input_names=PackedStringArray() )

Parses the expression and returns an Error code.

You can optionally specify names of variables that may appear in the expression with input_names, so that you can bind them when it gets executed.