Menu
CoddyTech

Initialization

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

A Lua constructor is an ordinary function returning a table. No special method runs unless the constructor calls it. GDScript new() creates an instance and invokes _init; _init initializes that instance rather than returning a replacement object. A typed field may have an initializer before construction. Keep normalization rules explicit instead of expecting types to enforce domain limits. Node._ready() is a scene lifecycle callback and is separate from construction. A RefCounted data object can be created without entering a scene. The example normalizes minutes, independently of the task's score clamp.

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

Lua file clock.lua:

local Clock = {}
Clock.__index = Clock
function Clock.new(minute)
  return setmetatable({minute = minute % 60}, Clock)
end
return Clock

Lua file main.lua:

local Clock = require("clock")
print(Clock.new(75).minute)

Lua output:

15

GDScript file demo_clock.gd:

class_name DemoClock
extends RefCounted
var minute: int
func _init(n: int) -> void:
	minute = n % 60

GDScript file main.gd:

extends Node

func _ready() -> void:
	print(DemoClock.new(75).minute)

GDScript output:

15
challenge icon

Challenge

Easy

Implement BoundedScore._init(initial:int=0), storing max(initial,0) in value:int. Each instance owns its value. The solve function 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. 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:
	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))
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