evaluating_expressions.rst 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. .. _doc_evaluating_expressions:
  2. Evaluating expressions
  3. ======================
  4. Godot provides an :ref:`class_Expression` class you can use to evaluate expressions.
  5. An expression can be:
  6. - A mathematical expression such as ``(2 + 4) * 16/4.0``.
  7. - A built-in method call like ``deg_to_rad(90)``.
  8. - A method call on an user-provided script like ``update_health()``,
  9. if ``base_instance`` is set to a value other than ``null`` when calling
  10. :ref:`Expression.execute() <class_Expression_method_execute>`.
  11. .. note::
  12. The Expression class is independent from GDScript.
  13. It's available even if you compile Godot with the GDScript module disabled.
  14. Basic usage
  15. -----------
  16. To evaluate a mathematical expression, use::
  17. var expression = Expression.new()
  18. expression.parse("20 + 10*2 - 5/2.0")
  19. var result = expression.execute()
  20. print(result) # 37.5
  21. The following operators are available:
  22. +------------------------+-------------------------------------------------------------------------------------+
  23. | Operator | Notes |
  24. +========================+=====================================================================================+
  25. | Addition ``+`` | Can also be used to concatenate strings and arrays: |
  26. | | - ``"hello" + " world"`` = ``hello world`` |
  27. | | - ``[1, 2] + [3, 4]`` = ``[1, 2, 3, 4]`` |
  28. +------------------------+-------------------------------------------------------------------------------------+
  29. | Subtraction (``-``) | |
  30. +------------------------+-------------------------------------------------------------------------------------+
  31. | Multiplication (``*``) | |
  32. +------------------------+-------------------------------------------------------------------------------------+
  33. | Division (``/``) | Performs and integer division if both operands are integers. |
  34. | | If at least one of them is a floating-point number, returns a floating-point value. |
  35. +------------------------+-------------------------------------------------------------------------------------+
  36. | Modulo (``%``) | Returns the remainder of an integer division. |
  37. +------------------------+-------------------------------------------------------------------------------------+
  38. Spaces around operators are optional. Also, keep in mind the usual
  39. `order of operations <https://en.wikipedia.org/wiki/Order_of_operations>`__
  40. applies. Use parentheses to override the order of operations if needed.
  41. All the Variant types supported in Godot can be used: integers, floating-point
  42. numbers, strings, arrays, dictionaries, colors, vectors, …
  43. Arrays and dictionaries can be indexed like in GDScript::
  44. # Returns 1.
  45. [1, 2][0]
  46. # Returns 3. Negative indices can be used to count from the end of the array.
  47. [1, 3][-1]
  48. # Returns "green".
  49. {"favorite_color": "green"}["favorite_color"]
  50. # All 3 lines below return 7.0 (Vector3 is floating-point).
  51. Vector3(5, 6, 7)[2]
  52. Vector3(5, 6, 7)["z"]
  53. Vector3(5, 6, 7).z
  54. Passing variables to an expression
  55. ----------------------------------
  56. You can pass variables to an expression. These variables will then
  57. become available in the expression's "context" and will be substituted when used
  58. in the expression::
  59. var expression = Expression.new()
  60. # Define the variable names first in the second parameter of `parse()`.
  61. # In this example, we use `x` for the variable name.
  62. expression.parse("20 + 2 * x", ["x"])
  63. # Then define the variable values in the first parameter of `execute()`.
  64. # Here, `x` is assigned the integer value 5.
  65. var result = expression.execute([5])
  66. print(result) # 30
  67. Both the variable names and variable values **must** be specified as an array,
  68. even if you only define one variable. Also, variable names are **case-sensitive**.
  69. Setting a base instance for the expression
  70. ------------------------------------------
  71. By default, an expression has a base instance of ``null``. This means the
  72. expression has no base instance associated to it.
  73. When calling :ref:`Expression.execute() <class_Expression_method_execute>`,
  74. you can set the value of the ``base_instance`` parameter to a specific object
  75. instance such as ``self``, another script instance or even a singleton::
  76. func double(number):
  77. return number * 2
  78. func _ready():
  79. var expression = Expression.new()
  80. expression.parse("double(10)")
  81. # This won't work since we're not passing the current script as the base instance.
  82. var result = expression.execute([], null)
  83. print(result) # null
  84. # This will work since we're passing the current script (i.e. self)
  85. # as the base instance.
  86. result = expression.execute([], self)
  87. print(result) # 20
  88. Associating a base instance allows doing the following:
  89. - Reference the instance's constants (``const``) in the expression.
  90. - Reference the instance's member variables (``var``) in the expression.
  91. - Call methods defined in the instance and use their return values in the expression.
  92. .. warning::
  93. Setting a base instance to a value other than ``null`` allows referencing
  94. constants, member variables, and calling all methods defined in the script
  95. attached to the instance. Allowing users to enter expressions may allow
  96. cheating in your game, or may even introduce security vulnerabilities if you
  97. allow arbitrary clients to run expressions on other players' devices.
  98. Example script
  99. --------------
  100. The script below demonstrates what the Expression class is capable of::
  101. const DAYS_IN_YEAR = 365
  102. var script_member_variable = 1000
  103. func _ready():
  104. # Constant mathexpression.
  105. evaluate("2 + 2")
  106. # Math expression with variables.
  107. evaluate("x + y", ["x", "y"], [60, 100])
  108. # Call built-in method (built-in math function call).
  109. evaluate("deg_to_rad(90)")
  110. # Call user method (defined in the script).
  111. # We can do this because the expression execution is bound to `self`
  112. # in the `evaluate()` method.
  113. # Since this user method returns a value, we can use it in math expressions.
  114. evaluate("call_me() + DAYS_IN_YEAR + script_member_variable")
  115. evaluate("call_me(42)")
  116. evaluate("call_me('some string')")
  117. func evaluate(command, variable_names = [], variable_values = []) -> void:
  118. var expression = Expression.new()
  119. var error = expression.parse(command, variable_names)
  120. if error != OK:
  121. push_error(expression.get_error_text())
  122. return
  123. var result = expression.execute(variable_values, self)
  124. if not expression.has_execute_failed():
  125. print(str(result))
  126. func call_me(argument = null):
  127. print("\nYou called 'call_me()' in the expression text.")
  128. if argument:
  129. print("Argument passed: %s" % argument)
  130. # The method's return value is also the expression's return value.
  131. return 0
  132. The output from the script will be::
  133. 4
  134. 160
  135. 1.5707963267949
  136. You called 'call_me()' in the expression text.
  137. 1365
  138. You called 'call_me()' in the expression text.
  139. Argument passed: 42
  140. 0
  141. You called 'call_me()' in the expression text.
  142. Argument passed: some string
  143. 0
  144. Built-in functions
  145. ------------------
  146. Most methods available in the :ref:`class_@GDScript` scope are available in the
  147. Expression class, even if no base instance is bound to the expression.
  148. The same parameters and return types are available.
  149. However, unlike GDScript, parameters are **always required** even if they're
  150. specified as being optional in the class reference. In contrast, this
  151. restriction on arguments doesn't apply to user-made functions when you bind a
  152. base instance to the expression.