Menu
CoddyTech

Scripts as Classes

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

Rust structs and impl blocks define data and behavior; constructing a struct ordinarily creates an owned value. GDScript scripts define reference-like objects and class_name registers their types. Rc<RefCell<T>> explicitly models shared mutable identity in the Rust comparison. Keep the ownership mechanism visible instead of treating a moved struct as an alias. Each named GDScript helper belongs in its required file.

Complete Rust 2021 program; compile main.rs with the listed sibling modules:

Rust file token.rs:

pub struct Token { pub text:String }

Rust file main.rs:

mod token;
use std::{rc::Rc,cell::RefCell};
fn main() { let a=Rc::new(RefCell::new(token::Token{text:"blue".into()})); let b=Rc::clone(&a); b.borrow_mut().text="gold".into(); println!("{}",a.borrow().text); }

Rust output:

gold

GDScript example file demo_token.gd:

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

GDScript example 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 0 and label:String initially empty. Solve 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. 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:
	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 Rust Developers

Practice on your own: Online GDScript compiler