array_last 함수 설명
array_last
함수는 주어진 배열의 마지막 요소를 반환하는 함수입니다. 즉, 배열의 마지막 인덱스인 array_length(array) - 1
에 있는 요소를 가져옵니다. 이 함수는 배열을 수정하지 않습니다. 배열의 마지막 요소를 읽으면서 제거하려면 array_pop
함수를 사용해야 합니다.
문법
array_last(array);
매개변수
매개변수 | 타입 | 설명 |
---|---|---|
array | Array | 마지막 값을 가져올 배열 |
반환값
- Any: 배열이 보유할 수 있는 유효한 데이터 타입
- undefined: 배열이 비어 있을 경우
예제
var _last_added_enemy = array_last(enemies);
with (_last_added_enemy) {
show_debug_message(string(id) + " is the last enemy in the array.");
}
위의 코드는 enemies
배열에 추가된 마지막 적 인스턴스를 가져와서 임시 변수 _last_added_enemy
에 저장합니다. 그런 다음 해당 인스턴스가 자신의 ID를 포함한 디버그 메시지를 표시하도록 합니다.
활용 예제
1. 마지막 요소 출력
var last_item = array_last(my_array);
show_debug_message("The last item is: " + string(last_item));
2. 배열이 비어 있는지 확인
if (array_length(my_array) > 0) {
var last_item = array_last(my_array);
show_debug_message("Last item: " + string(last_item));
} else {
show_debug_message("The array is empty.");
}
3. 마지막 요소를 다른 배열로 이동
if (array_length(source_array) > 0) {
var last_item = array_last(source_array);
array_push(destination_array, last_item);
}
4. 마지막 요소 제거 후 사용
if (array_length(my_array) > 0) {
var last_item = array_last(my_array);
array_pop(my_array); // 마지막 요소 제거
show_debug_message("Removed last item: " + string(last_item));
}
5. 여러 배열에서 마지막 요소 비교
var last_enemy = array_last(enemies);
var last_item = array_last(items);
if (last_enemy == last_item) {
show_debug_message("The last enemy and last item are the same!");
}
이와 같이 array_last
함수를 활용하여 다양한 상황에서 배열의 마지막 요소를 쉽게 다룰 수 있습니다.