Menu
CoddyTech

Instance Methods

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

Lua colon syntax passes the receiver implicitly at the call site and adds self in a function declaration. A dot call requires passing the receiver yourself. GDScript instance methods already have an implicit receiver; do not add an extra self parameter when porting a Lua colon method. A method may read state, mutate it, or return a value, and its contract should say which. Calls through aliases act on the same object. A static function has no instance receiver. The door example toggles a Boolean, separate from the task's numeric accumulation.

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

Lua file door.lua:

local Door = {}
Door.__index = Door
function Door.new() return setmetatable({open = false}, Door) end
function Door:toggle() self.open = not self.open end
return Door

Lua file main.lua:

local Door = require("door")
local d = Door.new()
d:toggle()
print(d.open)

Lua output:

true

GDScript file demo_door.gd:

class_name DemoDoor
extends RefCounted
var open: bool = false
func toggle() -> void:
	open = not open

GDScript file main.gd:

extends Node

func _ready() -> void:
	var door: DemoDoor = DemoDoor.new()
	door.toggle()
	print(door.open)

GDScript output:

true
challenge icon

Challenge

Easy

Implement RunningTotal with value initially zero, add(amount:int)->void and read()->int. The solve function adds each input integer. Separate instances stay 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 running_total.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: RunningTotal = RunningTotal.new()
	var b: RunningTotal = RunningTotal.new()
	a.add(5)
	a.add(-2)
	if a.read() != 3 or b.read() != 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