Evaluating expressions

Godot provides an Expression class you can use to evaluate expressions.

An expression can be:

  • A mathematical expression such as (2 + 4) * 16/4.0.

  • A built-in method call like deg_to_rad(90).

  • A method call on a user-provided script like update_health(), if base_instance is set to a value other than null when calling Expression.execute().

Note

The Expression class is independent from GDScript. It’s available even if you compile Godot with the GDScript module disabled.

Basic usage

To evaluate a mathematical expression, use:

  1. var expression = Expression.new()
  2. expression.parse("20 + 10*2 - 5/2.0")
  3. var result = expression.execute()
  4. print(result) # 37.5

The following operators are available:

Operator

Notes

Addition +

Can also be used to concatenate strings and arrays: - “hello” + “ world” = hello world - [1, 2] + [3, 4] = [1, 2, 3, 4]

Subtraction (-)

Multiplication (*)

Division (/)

Performs and integer division if both operands are integers. If at least one of them is a floating-point number, returns a floating-point value.

Remainder (%)

Returns the remainder of an integer division (modulo). The result will always have the sign of the dividend.

Spaces around operators are optional. Also, keep in mind the usual order of operations applies. Use parentheses to override the order of operations if needed.

All the Variant types supported in Godot can be used: integers, floating-point numbers, strings, arrays, dictionaries, colors, vectors, …

Arrays and dictionaries can be indexed like in GDScript:

  1. # Returns 1.
  2. [1, 2][0]
  3. # Returns 3. Negative indices can be used to count from the end of the array.
  4. [1, 3][-1]
  5. # Returns "green".
  6. {"favorite_color": "green"}["favorite_color"]
  7. # All 3 lines below return 7.0 (Vector3 is floating-point).
  8. Vector3(5, 6, 7)[2]
  9. Vector3(5, 6, 7)["z"]
  10. Vector3(5, 6, 7).z

Passing variables to an expression

You can pass variables to an expression. These variables will then become available in the expression’s “context” and will be substituted when used in the expression:

  1. var expression = Expression.new()
  2. # Define the variable names first in the second parameter of `parse()`.
  3. # In this example, we use `x` for the variable name.
  4. expression.parse("20 + 2 * x", ["x"])
  5. # Then define the variable values in the first parameter of `execute()`.
  6. # Here, `x` is assigned the integer value 5.
  7. var result = expression.execute([5])
  8. print(result) # 30

Both the variable names and variable values must be specified as an array, even if you only define one variable. Also, variable names are case-sensitive.

Setting a base instance for the expression

By default, an expression has a base instance of null. This means the expression has no base instance associated to it.

When calling Expression.execute(), you can set the value of the base_instance parameter to a specific object instance such as self, another script instance or even a singleton:

  1. func double(number):
  2. return number * 2
  3. func _ready():
  4. var expression = Expression.new()
  5. expression.parse("double(10)")
  6. # This won't work since we're not passing the current script as the base instance.
  7. var result = expression.execute([], null)
  8. print(result) # null
  9. # This will work since we're passing the current script (i.e. self)
  10. # as the base instance.
  11. result = expression.execute([], self)
  12. print(result) # 20

Associating a base instance allows doing the following:

  • Reference the instance’s constants (const) in the expression.

  • Reference the instance’s member variables (var) in the expression.

  • Call methods defined in the instance and use their return values in the expression.

Warning

Setting a base instance to a value other than null allows referencing constants, member variables, and calling all methods defined in the script attached to the instance. Allowing users to enter expressions may allow cheating in your game, or may even introduce security vulnerabilities if you allow arbitrary clients to run expressions on other players’ devices.

Example script

The script below demonstrates what the Expression class is capable of:

  1. const DAYS_IN_YEAR = 365
  2. var script_member_variable = 1000
  3. func _ready():
  4. # Constant mathexpression.
  5. evaluate("2 + 2")
  6. # Math expression with variables.
  7. evaluate("x + y", ["x", "y"], [60, 100])
  8. # Call built-in method (built-in math function call).
  9. evaluate("deg_to_rad(90)")
  10. # Call user method (defined in the script).
  11. # We can do this because the expression execution is bound to `self`
  12. # in the `evaluate()` method.
  13. # Since this user method returns a value, we can use it in math expressions.
  14. evaluate("call_me() + DAYS_IN_YEAR + script_member_variable")
  15. evaluate("call_me(42)")
  16. evaluate("call_me('some string')")
  17. func evaluate(command, variable_names = [], variable_values = []) -> void:
  18. var expression = Expression.new()
  19. var error = expression.parse(command, variable_names)
  20. if error != OK:
  21. push_error(expression.get_error_text())
  22. return
  23. var result = expression.execute(variable_values, self)
  24. if not expression.has_execute_failed():
  25. print(str(result))
  26. func call_me(argument = null):
  27. print("\nYou called 'call_me()' in the expression text.")
  28. if argument:
  29. print("Argument passed: %s" % argument)
  30. # The method's return value is also the expression's return value.
  31. return 0

The output from the script will be:

  1. 4
  2. 160
  3. 1.5707963267949
  4. You called 'call_me()' in the expression text.
  5. 1365
  6. You called 'call_me()' in the expression text.
  7. Argument passed: 42
  8. 0
  9. You called 'call_me()' in the expression text.
  10. Argument passed: some string
  11. 0

Built-in functions

All methods in the Global Scope are available in the Expression class, even if no base instance is bound to the expression. The same parameters and return types are available.

However, unlike GDScript, parameters are always required even if they’re specified as being optional in the class reference. In contrast, this restriction on arguments doesn’t apply to user-made functions when you bind a base instance to the expression.


User-contributed notes

Please read the User-contributed notes policy before submitting a comment.

Previous Next