Initialization
Lesson 23 of 48 in Coddy's GDScript for Luau Developers course.
A Luau constructor named new is an ordinary function chosen by convention; it returns the created table. GDScript new invokes _init for initialization, and _init does not return a replacement instance. Field defaults run as part of construction. RefCounted data objects do not need to enter a scene tree: _ready belongs to the Node lifecycle, not ordinary data construction. A numeric annotation does not establish a domain rule; normalization and validation still need explicit code.
Complete Luau comparison. Save the files together and run main.luau with the Luau CLI:
File clock.luau:
local Clock = {}
function Clock.new(minute: number)
return {minute = minute % 60}
end
return ClockFile main.luau:
local Clock = require("./clock")
print(Clock.new(75).minute)Luau output:
15Complete GDScript comparison:
File demo_clock.gd:
class_name DemoClock
extends RefCounted
var minute: int
func _init(n: int) -> void:
minute = n % 60File main.gd:
extends Node
func _ready() -> void:
print(DemoClock.new(75).minute)GDScript output:
15Challenge
EasyImplement BoundedScore._init(initial:int=0), storing max(initial,0) in value:int. Each instance owns its value. Solve returns values for [initial] and a default instance.
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 bounded_score.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:
if BoundedScore.new(-7).value != 0 or BoundedScore.new(8).value != 8 or BoundedScore.new().value != 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))
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in GDScript for Luau 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 Count5Objects and State
Scripts as ClassesInitializationInstance MethodsRecap: Independent BasketsProperty SettersPractice on your own: Online GDScript compiler