Composed Objects
Lesson 29 of 48 in Coddy's GDScript for Lua Developers course.
Lua tables can store references to other tables, making composition possible without metatable inheritance. GDScript members can likewise hold collaborating objects. Neither assignment clones the collaborator. A constructor parameter makes that relationship explicit and lets a caller substitute behavior. Lua's tracing collector can reclaim unreachable table cycles, whereas mutual strong references between RefCounted objects can leak. Keep ownership directed or use a weak reference for a back link. Here an envelope observes a changed note through a shared reference; the task delegates a numeric policy operation instead.
Complete Lua 5.1 comparison. Run main.lua from the directory containing all shown files:
Lua file note.lua:
local Note = {}
function Note.new() return {text = "a"} end
return Note
Lua file envelope.lua:
local Envelope = {}
function Envelope.new(note) return {note = note} end
return Envelope
Lua file 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 output:
bGDScript file demo_note.gd:
class_name DemoNote
extends RefCounted
var text: String = "a"
GDScript file demo_envelope.gd:
class_name DemoEnvelope
extends RefCounted
var note: DemoNote
func _init(value: DemoNote) -> void:
note = value
GDScript file 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 output:
bChallenge
EasyImplement RateRule(cents:int) with cost(units:int). BillBox(rule:RateRule) stores the supplied rule and total(units:int) delegates to it. Changing rule.cents afterward must affect the bill. The solve function uses [rate,units].
Input is one JSON array on stdin. The locked main parses it, calls the public APIs and prints result= followed by the returned text and a newline. No helper should print. Independent fixed probes verify required API behavior before the input case; they do not enforce implementation style.
Your code goes in rate_rule.gd, bill_box.gd, exercise.gd. The supplied main.gd cannot be edited. Keep each class_name type in its named file.
Try it yourself
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))
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in GDScript for Lua Developers
1Scripts and Scalar Values
Run Script FilesText and CommentsBindings and TypesInteger ArithmeticBoolean ResultsRecap: Stock Label2Flow and Functions
Branches and ValuesPattern MatchingLoops and RangesTyped FunctionsDefault ArgumentsRecap: Command Count3Collection Ownership
Array OperationsTyped ArraysShared and Copied ArraysDictionary PresenceDictionary TraversalRecap: Word Frequencies6Object Relationships
Inheritance and SuperDynamic DispatchComposed ObjectsRecap: Tiered FeesSignals and PayloadsPractice on your own: Online GDScript compiler