데이터로 작업할 때 한 데이터 타입에서 다른 데이터 타입으로 변수를 변환해야 하는 경우가 종종 있습니다. 예를 들어 계산 결과를 표시하려면 float에서 string으로 변환해야 합니다.
Verse 내의 모든 타입 변환은 명시적이므로, 오브젝트를 다른 데이터 타입으로 변환하려면 ToString()과 같은 함수를 사용하거나 곱하기(*) 같은 연산자를 사용해야 합니다. 한 타입을 다른 타입으로 명시적으로 변환하는 것을 타입 형변환이라고도 합니다.
플로트를 인티저로 변환하기
float에서 int로 변환하려면 부동 소수점 수에서 정수로 변환하는 방법을 명시적으로 지정하는 함수가 필요합니다. 다음 함수들은 모두 변환을 처리하지만 작동 방식은 각기 다릅니다. 주어진 상황에 어떤 것이 가장 적합한지 결정하는 것은 사용자의 몫입니다.
이 예시에서는 or 연산자를 사용하여 서로 다른 함수가 4개의 float 리터럴 값을 int 값으로 변환해 실패 컨텍스트를 만듭니다. 그런 다음 set가 int 타입 변수에 값을 할당합니다.
# The Int[] method has the <decides> effect,
# This means that we need to account for failure as it is a failable expression.
# This results in the following
# var WoodInt:int = failable expression or the value if it fails.
var WoodCollectedFloat:float = 10.5
var WoodInt:int = Int[WoodCollectedFloat] or 0
Print("Printing WoodInt Value (10): {WoodInt}")
# Similar to Int[], Floor[], Ceil[], and Round[] also have the <decides> effect
이 예시에서는 if 표현식이 이러한 실패 가능 함수의 실패 컨텍스트를 만들고, set가 int 타입 변수에 값을 할당합니다.
var WoodCollected:int = 0
var StoneCollected:int = 0
var GoldCollected:int = 0
var FoodCollected:int = 0
if:
# This block is the condition of the if expression
# Which creates the failure context
# If any fail, the entire chain of execution is rolled back
# And the else branch, if it exists, is executed
인티저를 플로트로 변환하기
곱하기 연산자(*)는 곱셈을 수행하기 전에 정수를 부동 소수점 수로 변환합니다. int에서 float 데이터 타입으로 변환하는 방법은 정수에 1.0을 곱하는 것입니다.
이 코드는 int 변수 StartingPositionX를 곱셈을 통해 float로 변환하여 vector3 변수 선언에 사용할 수 있도록 합니다. 데이터 타입 vector3은 X, Y, Z 필드에 float 타입 값이 필요합니다.
# Required for the vector3 type
using { /UnrealEngine.com/Temporary/SpatialMath}
var StartingPositionX:int = 960
# CurrentX = 960.0
var CurrentX:float = StartingPositionX * 1.0
var CurrentPosition:vector3 = vector3{X := CurrentX, Y := 0.0, Z := 0.0}
Print("CurrentX: {CurrentX}")스트링으로 변환
ToString() 함수 또는 스트링 보간을 사용하여 여러 데이터 타입을 string으로 변환할 수 있으며, 이는 ToString() 함수를 호출합니다. 현재 Verse에서는 다음 타입에 ToString() 함수가 내장되어 있습니다.
float
Int
[]char
char
vector2
vector3
rotation
이 예시에서는 스트링 보간과 ToString() 함수를 통해 변수가 스트링으로 변환되는 것을 볼 수 있습니다. 스트링 보간은 ToString()을 호출하므로 두 방법 모두 동일한 결과를 가져옵니다.
var WoodCollected:int = 100
# Convert using string interpolation
Print("WoodCollected: { WoodCollected }")
# or ToString() function
Print("WoodCollected: " + ToString(WoodCollected))
var InitialDistance:float = 3.625
# Convert using string interpolation
Print("InitialDistance: { InitialDistance }")
# or ToString() function
커스텀 데이터 타입을 스트링으로 변환
커스텀 데이터 타입은 데이터 타입에 ToString(custom_type) 함수를 구현하여 스트링으로 변환할 수도 있습니다. ToString(custom_type) 함수가 있는 경우, 스트링 보간은 이 함수를 사용하여 데이터 타입을 스트링으로 자동 변환합니다.
다음은 열매 enum에 대한 커스텀 ToString() 함수의 예시입니다.
fruit := enum:
Apple
Banana
Strawberry
ToString(Fruit: fruit):string =
case(Fruit):
fruit.Apple => "Apple"
fruit.Banana => "Banana"
fruit.Strawberry => "Strawberry"
다음은 커스텀 클래스에 대한 커스텀 ToString() 함수의 예시입니다. ToString() 함수가 waypoint 클래스 외부에서 선언된 것을 확인할 수 있습니다. SetDestination() 함수에서 Destination의 스트링 보간은 커스텀 ToString() 함수를 호출하고 있습니다.
# Custom class with constructor and a ToString() function
waypoint := class():
DisplayName:string
Position:vector3 = vector3{}
MakeWaypoint<constructor>(Name:string, X:float, Y:float, Z:float) := waypoint:
DisplayName := Name
Position := vector3{X := X, Y := Y, Z := Z}
ToString(Waypoint: waypoint):string =
오브젝트 레퍼런스를 다른 타입으로 변환
다음 구문을 사용하여 오브젝트에 대한 레퍼런스(또는 타입 형변환)를 다른 클래스 또는 인터페이스로 명시적으로 변환할 수 있습니다.
if (NewObjectReference := object_type_to_cast_to[ObjectReference]) {}object_type_to_cast_to는 레퍼런스를 변환하려는 클래스 또는 인터페이스를 나타냅니다. 오브젝트를 지정된 타입으로 변환할 수 없는 경우 타입 변환이 실패하므로 실패 가능 표현식입니다. 클래스가 오브젝트 타입, 수퍼클래스 타입 또는 오브젝트 클래스가 구현하는 인터페이스와 일치하지 않으면 오브젝트 레퍼런스를 클래스로 변환하려는 시도가 실패합니다.
이 코드는 인터페이스 positionable, positionable에서 상속되는 추상 클래스 shape, shape의 두 서브클래스 triangle과 square를 선언합니다. 그런 다음 MyShape라는 square 타입 오브젝트를 생성하고 이를 다른 세 가지 타입으로 타입 형변환하려고 시도합니다. 다음은 결과 분석입니다.
| square 타입 형변환 | 결과 |
|---|---|
|
|
|
|
|
|
# Class and interface definitions
positionable := interface() {}
shape := class<abstract>(positionable) {}
triangle := class(shape) {}
square := class(shape) {}
# Create a square object referenced using the superclass type shape
MyShape:shape = square{}
# This will succeed since MySquare is a square object
마지막 예시에서는 타입 형변환이 작동하지만 필수는 아닙니다. 이 코드도 같은 결과를 가져올 것입니다.
MyDrawable:positionable = MyShape타입 변환을 사용한 예시
UEFN에서 오브젝트 타입 형변환의 한 가지 사용 사례는 특정 타입의 액터를 찾아서 타입에 따라 함수를 호출하는 것입니다. 방법을 알아보려면 게임플레이 태그 문서에서 게임플레이 태그로 액터 찾기를 참고하세요.