합성 객체
Coddy의 Lua 개발자를 위한 GDScript 코스 레슨. 48개 중 29번째.
Lua 테이블은 다른 테이블에 대한 참조를 저장할 수 있어 메타테이블 상속 없이도 컴포지션을 구현할 수 있습니다. GDScript 멤버도 마찬가지로 협력 객체를 보유할 수 있습니다. 어느 쪽이든 대입한다고 해서 협력 객체의 복제본이 만들어지는 것은 아닙니다. 생성자 매개변수를 사용하면 이러한 관계가 명확해지고, 호출자가 동작을 대체할 수 있습니다. Lua의 추적 가비지 컬렉터는 도달할 수 없는 테이블 순환 참조를 회수할 수 있지만, RefCounted 객체 간의 상호 강한 참조는 메모리 누수를 일으킬 수 있습니다. 소유권의 방향을 한쪽으로 유지하거나 역방향 참조에 약한 참조를 사용하세요. 여기서는 공유 참조를 통해 봉투가 변경된 메모를 확인합니다. 이어지는 작업에서는 숫자 정책 연산을 위임합니다.
Lua 5.1 비교 예제를 완성하세요. 표시된 모든 파일이 있는 디렉터리에서 main.lua를 실행하세요.
Lua 파일 note.lua:
local Note = {}
function Note.new() return {text = "a"} end
return Note
Lua 파일 envelope.lua:
local Envelope = {}
function Envelope.new(note) return {note = note} end
return Envelope
Lua 파일 main.lua:
local Note = require("note")
local Envelope = require("envelope")
local n = Note.new()
local e = Envelope.new(n)
n.text = "b"
print(e.note.text)
Lua 출력:
bGDScript 파일 demo_note.gd:
class_name DemoNote
extends RefCounted
var text: String = "a"
GDScript 파일 demo_envelope.gd:
class_name DemoEnvelope
extends RefCounted
var note: DemoNote
func _init(value: DemoNote) -> void:
note = value
GDScript 파일 main.gd:
extends Node
func _ready() -> void:
var note: DemoNote = DemoNote.new()
var envelope: DemoEnvelope = DemoEnvelope.new(note)
note.text = "b"
print(envelope.note.text)
GDScript 출력:
b챌린지
쉬움RateRule(cents:int)와 cost(units:int)를 구현하세요. BillBox(rule:RateRule)는 전달된 규칙을 저장하고, total(units:int)은 해당 규칙에 처리를 위임합니다. 이후에 rule.cents를 변경하면 청구 금액에 반영되어야 합니다. solve 함수는 [rate,units]를 사용합니다.
표준 입력에는 JSON 배열 하나가 입력됩니다. 수정할 수 없는 main은 배열을 파싱하고, 공개 API를 호출한 다음 반환된 텍스트 앞에 result=를 붙여 개행 문자와 함께 출력합니다. 도우미 함수는 아무것도 출력하면 안 됩니다. 독립적인 고정 테스트는 입력 사례를 실행하기 전에 필수 API 동작을 확인하며, 구현 방식은 강제하지 않습니다.
코드는 rate_rule.gd, bill_box.gd, exercise.gd에 작성하세요. 제공된 main.gd는 수정할 수 없습니다. 각 class_name 형식은 이름에 해당하는 파일에 두세요.
직접 해보기
extends Node
func contract_ok(data: Array) -> bool:
var rule: RateRule = RateRule.new(2)
var bill: BillBox = BillBox.new(rule)
rule.cents = 7
if rule.cost(3) != 21 or bill.total(3) != 21: 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))
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Lua 개발자를 위한 GDScript의 모든 레슨
직접 연습해 보세요: 온라인 GDScript 컴파일러