Menu
CoddyTech

Composed Objects

Lesson 29 of 48 in Coddy's GDScript for Luau Developers course.

Both languages can compose objects by storing references to collaborators. A Luau table field and a GDScript object property normally share the supplied object rather than copying it. Define whether a constructor adopts a reference or constructs independent state. Luau uses tracing garbage collection, so a reference cycle alone does not keep an otherwise unreachable group alive. GDScript RefCounted does not reclaim strong reference cycles automatically. Keep ownership direction explicit and use weak references where a back-reference must not own the object.

Complete Luau comparison. Save the files together and run main.luau with the Luau CLI:

File note.luau:

local Note = {}
function Note.new(text: string)
    return {text = text}
end
return Note

File envelope.luau:

local Envelope = {}
function Envelope.new(note)
    return {note = note}
end
return Envelope

File 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 output:

b

Complete GDScript comparison:

File demo_note.gd:

class_name DemoNote
extends RefCounted
var text: String = "a"

File demo_envelope.gd:

class_name DemoEnvelope
extends RefCounted
var note: DemoNote
func _init(value: DemoNote) -> void:
	note = value

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:

b
challenge icon

Challenge

Easy

Implement 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. Solve 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. main.gd holds the supplied input/output code and 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))
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in GDScript for Luau Developers

Practice on your own: Online GDScript compiler