Menu
CoddyTech

Reference Lifetimes

Lesson 40 of 48 in Coddy's GDScript for Lua Developers course.

Lua uses tracing garbage collection and can collect unreachable cycles of tables. Weak tables let references avoid keeping their keys or values alive; __mode = "v" makes values weak. Collection timing is not the same as assigning nil. GDScript RefCounted objects use reference counts and do not automatically reclaim mutual strong cycles. WeakRef observes an object without retaining it and returns null once it is gone. Another strong reference keeps an object alive in both demonstrations. Nodes have a different lifecycle and need ownership-aware freeing. Use RefCounted for ordinary task data and avoid strong back-reference cycles.

Complete Lua 5.1 comparison. Run main.lua from the directory containing all shown files:

Lua file main.lua:

local a = {}
local weak = setmetatable({a}, {__mode = "v"})
local b = a
a = nil
collectgarbage("collect")
print(weak[1] == b)

Lua output:

true

GDScript file main.gd:

extends Node

func _ready() -> void:
	var a: RefCounted = RefCounted.new()
	var weak: WeakRef = weakref(a)
	var b: RefCounted = a
	a = null
	print(weak.get_ref() == b)

GDScript output:

true
challenge icon

Challenge

Easy

Implement OwnedNote(text:String) and static NoteViews.label(note:OwnedNote)->String. Return missing for null; otherwise return note.text. The solve function creates a note for a string input, or passes null. Do not manually free RefCounted instances.

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 owned_note.gd, note_views.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 original: OwnedNote = OwnedNote.new("a")
	var alias: OwnedNote = original
	original = null
	if NoteViews.label(alias) != "a" or NoteViews.label(null) != "missing": 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 Lua Developers

Practice on your own: Online GDScript compiler