신호와 페이로드
Coddy의 Ruby 개발자를 위한 GDScript 코스 레슨. 48개 중 31번째.
Ruby의 콜백 목록과 블록은 알림을 구현할 수 있으며, GDScript에는 내장 시그널과 Callable 연결 기능이 있습니다. 일반적인 지연되지 않는 전달은 emit 중에 동기적으로 이루어집니다. 이벤트 라이브러리는 다른 스케줄링 방식을 선택할 수 있으므로, 각 라이브러리의 계약을 명확히 비교하세요. 관찰자가 상태를 확인해야 한다면 알림 전에 상태를 업데이트하고, 페이로드 순서를 유지하며, 관계가 끝나면 연결을 해제하세요. 이 예제는 메시지 하나를 전달합니다.
Ruby 3.3 완성된 비교 (main.rb 실행):
seen=[]; listeners=[->(text) { seen << text }]; listeners.each { |listener| listener.call("hello") }; listeners.clear; puts seen[0]
Ruby 출력:
helloGDScript 예제 파일 demo_notice.gd:
class_name DemoNotice
extends RefCounted
signal message(text: String)GDScript 예제 파일 main.gd:
extends Node
func _ready() -> void:
var source: DemoNotice = DemoNotice.new()
var seen: Array = []
var callback: Callable = func(text: String) -> void: seen.append(text)
source.message.connect(callback)
source.message.emit("hello")
source.message.disconnect(callback)
print(seen[0])GDScript 출력:
hello챌린지
쉬움changed(value:int) 시그널이 있고 value가 처음에 0인 PulseSource를 구현하세요. set_value(n:int)는 n이 현재 값과 다를 때만 값을 업데이트한 후 changed를 한 번 내보내야 합니다. Solve는 입력값을 적용하고 최종 값을 반환합니다. 잠금된 프로브는 이벤트 페이로드와 횟수를 별도로 검증합니다.
입력은 stdin에 전달되는 하나의 JSON 배열입니다. 잠금된 main은 이를 파싱하고, 공개 API를 호출한 다음 result= 뒤에 반환된 텍스트를 붙여 출력하고 개행 문자를 출력합니다. 어떤 헬퍼도 출력해서는 안 됩니다. 독립적인 고정 프로브는 입력 사례를 실행하기 전에 필수 API 동작을 검증하며, 구현 스타일은 검사하지 않습니다.
코드는 pulse_source.gd와 exercise.gd에 작성하세요. main.gd에는 제공된 입력/출력 코드가 있으며 수정할 수 없습니다. 각 class_name 형식을 이름이 지정된 파일에 두세요.
직접 해보기
extends Node
func contract_ok(data: Array) -> bool:
var source: PulseSource = PulseSource.new()
var observed: Array = []
var record: Callable = func(n: int) -> void: observed.append(n)
source.changed.connect(record)
source.set_value(4)
source.set_value(4)
source.set_value(2)
source.changed.disconnect(record)
if observed != [4,2] or source.value != 2: return false
return true
func _ready() -> void:
var data: Array = JSON.parse_string(OS.read_string_from_stdin())
if not contract_ok(data):
print("API_CONTRACT_FAILED")
return
print("result=" + Exercise.solve(data))
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Ruby 개발자를 위한 GDScript의 모든 레슨
직접 연습해 보세요: 온라인 GDScript 컴파일러