정적 구조체 (Static Struct) 설명서
정적 구조체는 각 함수에서 정적 변수를 저장하는 역할을 합니다. 이 문서에서는 정적 구조체의 개념, 정적 체인, 자식과 부모 구조체 간 정적 변수의 동작에 대해 설명하고, 몇 가지 활용 예제를 제시합니다.
정적 구조체 이해하기
각 함수마다 자체의 정적 구조체가 있으며, 정적 변수를 이 구조체에 저장합니다. 정적 구조체는 다음과 같이 가져올 수 있습니다:
function counter() {
static count = 0;
return count++;
}
repeat (10) counter(); // counter()의 정적 구조체에서 값을 증가시킴
var _static_counter = static_get(counter);
위 코드에서 counter.count와 _static_counter.count는 같은 변수를 읽어옵니다.
정적 체인 (Static Chain)
생성자 상속을 사용할 때 각 생성자는 "정적 체인"을 형성합니다. 이는 각 자식 생성자가 부모와 연결되는 정적 구조체 체인입니다.
예를 들어, item 생성자와 그 자식 생성자 potion이 있다고 가정해 봅시다:
function item() constructor {}
function potion() : item() constructor {}
var _potion = new potion();
var _static_potion = static_get(potion);
potion의 정적 구조체를 가져오려면 static_get(potion)을 사용하면 됩니다. 이때, static_get(static_potion)을 호출하면 item의 정적 구조체를 얻을 수 있습니다.
부모와 자식 생성자 사이의 변수 이름 충돌
정적 변수는 정의된 생성자에 속하므로, 자식 생성자에서 부모 생성자의 정적 변수와 동일한 이름의 변수를 정의할 수 있습니다. 다음 예를 참고하세요:
function shape() constructor {
static count = 0;
count++;
static shapes = [];
array_push(shapes, self);
}
function rectangle() : shape() constructor {
static count = 0;
count++;
}
function square() : rectangle() constructor {
static count = 0;
count++;
}
function ellipse() : shape() constructor {
static count = 0;
count++;
}
점 연산자 사용하기
특정 변수를 구조체에서 찾고 싶을 때 점 연산자(struct.variable_name)를 사용합니다. 이 경우 비정적 변수가 존재하면 해당 변수를 반환하고, 그렇지 않으면 정적 체인을 탐색하여 이름이 같은 변수를 찾습니다. 만약 찾을 수 없으면 오류가 발생합니다.
function root() constructor {
static show = function() { show_debug_message("root"); }
}
function child() : root() constructor {}
function child_with_static_func() : root() constructor {
static show = function() { show_debug_message("child_with_static_func"); }
}
function child_with_func() : root() constructor {
show = function() { show_debug_message("child_with_func"); }
}
child1 = new child();
child1.show(); // "root" 출력
부모의 정적 변수 또는 메서드 접근하기
특정 상황에서는 자식 생성자에서 부모 생성자의 정적 변수나 메서드를 호출해야 할 수도 있습니다. 이 경우 다음과 같이 정적 체인을 거쳐 접근할 수 있습니다:
function parent() constructor {
static init = function() { show_debug_message("Parent Init!"); }
}
function child() : parent() constructor {
static init = function() {
var _static = static_get(self);
var _static_parent = static_get(_static);
_static_parent.init(); // 부모의 init() 호출
show_debug_message("Child Init!");
}
}
정적 구조체 변경하기
static_set 함수를 사용하면 다른 구조체의 정적 구조체를 변경할 수 있습니다. 이 기능은 JSON에서 구조체를 로드할 때 유용합니다. 다음과 같이 사용할 수 있습니다:
var my_struct = {}; // 빈 구조체
static_set(my_struct, item); // item 생성자의 정적 변수 적용
마무리
이 문서에서 정적 구조체, 정적 체인, 부모와 자식 간 정적 변수의 동작, 그리고 점 연산자 사용에 대해 설명했습니다. 게임 개발 및 프로그래밍에서 이 개념들을 활용하여 더 나은 구조체를 구축할 수 있습니다.
활용 예제
| 이름 | 설명 | 코드 예제 |
|---|---|---|
| 카운터 | 정적 변수를 사용하여 카운트 기능을 구현합니다. | gml function counter() {...} |
| 도형 | 다양한 도형 생성자에서 개별 카운트를 관리합니다. | gml function shape() {...} |
| 상속 | 부모 클래스와 자식 클래스 간의 정적 체인을 보여줍니다. | gml function parent() {...} |
이러한 예제를 통해 정적 구조체와 정적 체인을 활용해 보세요!