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.

표현식 평가하기

Godot는 표현식을 평가하는 데 사용할 수 있는 Expression 클래스를 제공합니다.

Expression 노드는 가능합니다:

  • ``(2 + 4) * 16/4.0``와 같은 수학적 표현입니다.

  • ``true && false``와 같은 부울 표현식입니다.

  • ``deg_to_rad(90)``와 같은 내장 메소드 호출.

  • Expression.execute() <class_Expression_method_execute>`를 호출할 때 ``base_instance``가 ``null` 이외의 값으로 설정된 경우 ``update_health()``와 같은 사용자 제공 스크립트에 대한 메서드 호출입니다.

참고

Expression 클래스는 GDScript와 독립적입니다. GDScript 모듈이 비활성화된 상태에서 Godot를 컴파일하더라도 사용할 수 있습니다.

기초적인 사용법

수학적 표현식을 평가하려면 다음을 사용하세요.

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

다음 연산자를 사용할 수 있습니다.

연산자

메모

추가 정보

문자열과 배열을 연결하는 데에도 사용할 수 있습니다. - "hello" + " world" = hello world - [1, 2] + [3, 4] = [1, 2, 3, 4]

빼기

스칼라 곱

Truevision Targa (.tga)

두 피연산자가 모두 정수이면 정수 나누기를 수행합니다. 그 중 하나 이상이 부동 소수점 숫자인 경우 부동 소수점 값을 반환합니다.

나머지(%)

정수 나누기(모듈로)의 나머지를 반환합니다. 결과에는 항상 배당금의 부호가 표시됩니다.

빼기

부울 AND의 결과를 반환합니다.

Truevision Targa (.tga)

부울 OR의 결과를 반환합니다.

빼기

부울 NOT의 결과를 반환합니다.

연산자 주위의 공백은 선택 사항입니다. 또한 일반적인 `작업 순서 <https://en.wikipedia.org/wiki/Order_of_operations>`__이 적용된다는 점을 명심하세요. 필요한 경우 괄호를 사용하여 작업 순서를 재정의합니다.

Godot에서 지원되는 모든 Variant 유형을 사용할 수 있습니다: 정수, 부동 소수점 숫자, 문자열, 배열, 사전, 색상, 벡터 등.

배열과 사전은 GDScript처럼 인덱싱될 수 있습니다:

# Returns 1.
[1, 2][0]

# Returns 3. Negative indices can be used to count from the end of the array.
[1, 3][-1]

# Returns "green".
{"favorite_color": "green"}["favorite_color"]

# All 3 lines below return 7.0 (Vector3 is floating-point).
Vector3(5, 6, 7)[2]
Vector3(5, 6, 7)["z"]
Vector3(5, 6, 7).z

변수를 표현식에 전달하기

표현식에 변수를 전달할 수 있습니다. 그런 다음 이러한 변수는 표현식의 "컨텍스트"에서 사용할 수 있게 되며 표현식에서 사용될 때 대체됩니다.

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

변수를 하나만 정의하는 경우에도 변수 이름과 변수 값 모두 반드시 배열로 지정해야 합니다. 또한 변수 이름은 **대소문자를 구분**합니다.

Godot 서버 만들기

기본적으로 표현식에는 ``null``의 기본 인스턴스가 있습니다. 이는 표현식에 연관된 기본 인스턴스가 없음을 의미합니다.

Expression.execute() <class_Expression_method_execute>`을 호출할 때 ``base_instance` 매개 변수의 값을 self, 다른 스크립트 인스턴스 또는 심지어 싱글톤와 같은 특정 개체 인스턴스로 설정할 수 있습니다.

func double(number):
    return number * 2


func _ready():
    var expression = Expression.new()
    expression.parse("double(10)")

    # This won't work since we're not passing the current script as the base instance.
    var result = expression.execute([], null)
    print(result)  # null

    # This will work since we're passing the current script (i.e. self)
    # as the base instance.
    result = expression.execute([], self)
    print(result)  # 20

기본 인스턴스를 연결하면 다음을 수행할 수 있습니다.

  • 표현식에서 인스턴스의 상수(const)를 참조하세요.

  • 표현식에서 인스턴스의 멤버 변수(var)를 참조하십시오.

  • 인스턴스에 정의된 메서드를 호출하고 해당 반환 값을 표현식에 사용합니다.

경고

기본 인스턴스를 null 이외의 값으로 설정하면 상수, 멤버 변수를 참조하고 인스턴스에 연결된 스크립트에 정의된 모든 메서드를 호출할 수 있습니다. 사용자가 표현식을 입력하도록 허용하면 게임에서 부정 행위가 허용될 수 있으며, 임의 클라이언트가 다른 플레이어의 장치에서 표현식을 실행하도록 허용하는 경우 보안 취약점이 발생할 수도 있습니다.

GDScript 예제

아래 스크립트는 Expression 클래스의 기능을 보여줍니다.

const DAYS_IN_YEAR = 365
var script_member_variable = 1000


func _ready():
    # Constant boolean expression.
    evaluate("true && false")
    # Boolean expression with variables.
    evaluate("!(a && b)", ["a", "b"], [true, false])

    # Constant mathexpression.
    evaluate("2 + 2")
    # Math expression with variables.
    evaluate("x + y", ["x", "y"], [60, 100])

    # Call built-in method (built-in math function call).
    evaluate("deg_to_rad(90)")

    # Call user method (defined in the script).
    # We can do this because the expression execution is bound to `self`
    # in the `evaluate()` method.
    # Since this user method returns a value, we can use it in math expressions.
    evaluate("call_me() + DAYS_IN_YEAR + script_member_variable")
    evaluate("call_me(42)")
    evaluate("call_me('some string')")


func evaluate(command, variable_names = [], variable_values = []) -> void:
    var expression = Expression.new()
    var error = expression.parse(command, variable_names)
    if error != OK:
        push_error(expression.get_error_text())
        return

    var result = expression.execute(variable_values, self)

    if not expression.has_execute_failed():
        print(str(result))


func call_me(argument = null):
    print("\nYou called 'call_me()' in the expression text.")
    if argument:
        print("Argument passed: %s" % argument)

    # The method's return value is also the expression's return value.
    return 0

스크립트로부터 출력은 다음과 같습니다:

false
true
4
160
1.5707963267949

You called 'call_me()' in the expression text.
1365

You called 'call_me()' in the expression text.
Argument passed: 42
0

You called 'call_me()' in the expression text.
Argument passed: some string
0

내장 함수

:ref:`Global Scope<class_@GlobalScope>`의 모든 메서드는 표현식에 바인딩된 기본 인스턴스가 없더라도 Expression 클래스에서 사용할 수 있습니다. 동일한 매개변수와 반환 유형을 사용할 수 있습니다.

그러나 GDScript와 달리 매개변수는 클래스 참조에서 선택사항으로 지정되더라도 **항상 필수**입니다. 대조적으로, 인수에 대한 이러한 제한은 기본 인스턴스를 표현식에 바인딩할 때 사용자가 만든 함수에는 적용되지 않습니다.