Menu
CoddyTech

Initialization

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

C# constructors use the type name; GDScript initializes instances through _init and calls it via ClassName.new(arguments). _init does not return a replacement object. RefCounted objects can be constructed without a scene tree. Node._ready is a different lifecycle callback associated with entering the tree, not a constructor substitute. Field types do not infer business validation rules. The sample normalizes a minute value, whereas the task clamps a score and also exercises a default constructor argument.

Complete C# comparison. Compile all listed C# files together; Program.Main is the entry point.

C# file DemoClock.cs:

public class DemoClock { public int Minute; public DemoClock(int n){Minute=n%60;} }

C# file Program.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
public static class Program {

public static void Main() {
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
Console.WriteLine(new DemoClock(75).Minute);
}
}

C# output:

15

GDScript example file demo_clock.gd:

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

GDScript example 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. 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))
quiz iconTest yourself

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

All lessons in GDScript for C# Developers

Practice on your own: Online GDScript compiler