Menu
CoddyTech

Dynamic Dispatch

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

A Lua caller can invoke any table value that supports the required method; a prototype chain is optional. Missing methods still fail, because trying to call nil is an error. GDScript can dispatch dynamically through Object.call, while static script types express known class relationships. Dynamic dispatch does not manufacture missing behavior. Either require the capability as part of the API or check it before use. Preserve the collaborator supplied by the caller instead of replacing it with a favorite concrete object. The bell example demonstrates a method contract independently of the task's fee policies.

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

Lua file bell.lua:

local Bell = {}
Bell.__index = Bell
function Bell.new() return setmetatable({}, Bell) end
function Bell:speak() return "ding" end
return Bell

Lua file main.lua:

local Bell = require("bell")
local function announce(obj) return obj:speak() end
print(announce(Bell.new()))

Lua output:

ding

GDScript file demo_bell.gd:

class_name DemoBell
extends RefCounted
func speak() -> String:
	return "ding"

GDScript file main.gd:

extends Node

func _ready() -> void:
	var bell: DemoBell = DemoBell.new()
	print(bell.call("speak"))

GDScript output:

ding
challenge icon

Challenge

Easy

FeeReader.total(policy:RefCounted,units:int)->int must invoke the supplied policy cost method. FlatPolicy.cost returns 5 regardless of units. The solve function uses FlatPolicy. The driver also supplies a different compatible policy.

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 fee_reader.gd, flat_policy.gd, exercise.gd. The supplied main.gd cannot be edited. Keep each class_name type in its named file.

Try it yourself

extends Node

class ProbePolicy extends RefCounted:
	func cost(units: int) -> int:
		return units * 4 + 1

func contract_ok(data: Array) -> bool:
	if FlatPolicy.new().cost(9) != 5 or FeeReader.total(ProbePolicy.new(),4) != 17: 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