Menu
CoddyTech

Scripts as Classes

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

Lua has no built-in class declaration. A common prototype pattern sets a table's __index to a method table, with setmetatable connecting each instance to it. Constructor functions decide which fields belong to each instance. GDScript instead treats each script as a class, and class_name registers its name. Instantiate with new() and extend RefCounted for ordinary data. One named type lives in each module file here. Assignment shares an instance in both languages; it does not invoke construction again. Avoid native Godot names such as Node or Timer for your own registered types.

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

Lua file token.lua:

local Token = {}
Token.__index = Token
function Token.new()
  return setmetatable({text = "blue"}, Token)
end
return Token

Lua file main.lua:

local Token = require("token")
local a = Token.new()
local b = a
b.text = "gold"
print(a.text)

Lua output:

gold

GDScript file demo_token.gd:

class_name DemoToken
extends RefCounted
var text: String = "blue"

GDScript file main.gd:

extends Node

func _ready() -> void:
	var a: DemoToken = DemoToken.new()
	var b: DemoToken = a
	b.text = "gold"
	print(a.text)

GDScript output:

gold
challenge icon

Challenge

Easy

Define ParcelRecord with weight:int initially zero and label:String initially empty. The solve function creates two records, sets the first from [label,weight], and returns label:weight:second_weight. Fields must be independent.

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 parcel_record.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 a: ParcelRecord = ParcelRecord.new()
	var b: ParcelRecord = ParcelRecord.new()
	if a.weight != 0 or a.label != "": return false
	a.weight = 7
	if b.weight != 0: 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