组合对象
Coddy 面向 Luau 开发者的 GDScript 课程的第 29 课,共 48 课。
这两种语言都可以通过存储对协作者的引用来组合对象。Luau 表字段和 GDScript 对象属性通常会共享提供的对象,而不是复制它。请明确构造函数是采用引用,还是创建独立状态。Luau 使用追踪式垃圾回收,因此仅有引用循环不会让原本无法访问的一组对象继续存活。GDScript 的 RefCounted 不会自动回收强引用循环。请明确所有权方向,并在反向引用不应拥有对象时使用弱引用。
完成 Luau 对比。将这些文件保存在一起,并使用 Luau CLI 运行 main.luau:
文件 note.luau:
local Note = {}
function Note.new(text: string)
return {text = text}
end
return Note文件 envelope.luau:
local Envelope = {}
function Envelope.new(note)
return {note = note}
end
return Envelope文件 main.luau:
local Note = require("./note")
local Envelope = require("./envelope")
local note = Note.new("a")
local envelope = Envelope.new(note)
note.text = "b"
print(envelope.note.text)Luau 输出:
b完成 GDScript 对比:
文件 demo_note.gd:
class_name DemoNote
extends RefCounted
var text: String = "a"文件 demo_envelope.gd:
class_name DemoEnvelope
extends RefCounted
var note: DemoNote
func _init(value: DemoNote) -> void:
note = value文件 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]。
输入是 stdin 上的一个 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))
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Luau 开发者的 GDScript中的所有课
自己练习: GDScript 在线编译器