Polymorphism by Protocol
Lesson 40 of 48 in Coddy's Lua for GDScript Developers course.
GDScript can call a method on a dynamically held object when that object supplies the expected behavior. A shared base class is not required for every such collaboration. Lua tables support the same style: a sender needs a callable send field with the agreed receiver and message parameters. The caller can process an email sender and an SMS sender through the same loop. Neither table needs to inherit from a common prototype. This is a behavioral contract, so spelling and signatures still matter. Godot's has_method can inspect objects; a Lua boundary can inspect whether type(sender.send) is "function" when validation is needed.
GDScript 4
extends SceneTree
class Email:
func send(message):
return "email:" + message
class Sms:
func send(message):
return "sms:" + message
func _init():
var results = PackedStringArray()
for sender in [Email.new(), Sms.new()]:
results.append(sender.send("ready"))
print("|".join(results))
quit()Lua 5.1
local email = {}
function email:send(message) return "email:" .. message end
local sms = {}
function sms:send(message) return "sms:" .. message end
local results = {}
for i, sender in ipairs({email, sms}) do
results[i] = sender:send("ready")
end
print(table.concat(results, "|"))Porting trap
A matching method name alone does not fix a mismatched receiver convention. Keep both implementations compatible with the same colon call.
Challenge
EasyInput is a message line. Implement email.lua and sms.lua, each returning a table with send(self,text). Prefix text with email: or sms:. The app calls both and returns outputs joined by a vertical bar. Empty message is valid.
Edit app.lua, email.lua, sms.lua. The visible locked main.lua reads stdin into a sequence of lines, calls app.run(lines), and prints its returned value with one final newline. Do not print diagnostics or change the module names. Empty input gives an empty sequence. All numeric inputs are small enough to avoid overflow.
Public API checks: Both channel modules must independently implement send(self, text), including empty text. The locked driver checks this behavior before calling app.run. These checks print nothing when successful.
Try it yourself
-- Public API checks
do
local email,sms=require("email"),require("sms")
assert(email:send("hi")=="email:hi" and sms:send("hi")=="sms:hi","both channels implement send")
assert(email:send("")=="email:" and sms:send("")=="sms:","send preserves empty messages")
end
local app = require("app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Lua for GDScript Developers
1First Lua Programs
Run Lua ModulesPrint and CommentNames and Local ScopeNumbers and ConversionStrings and Byte IndexesRecap: Format a Receipt4Functions and Closures
Functions and ReturnsDefaults and Missing ValuesMultiple Results and VarargsCallbacks and Captured StateRecap: Pricing Functions2Values and Decisions
null and Missing FieldsTruth and Default ValuesBranches and BoundsEquality and IdentityRecap: Admission Rules5Tables as Collections
Arrays as Dense TablesDictionaries and pairsSets and MembershipAliasing and Shallow CopiesRecap: Count Inventory8Composition and Object Lookup
Readable ObjectsComposition and DelegationPrototype Lookup ChainsPolymorphism by ProtocolValue Equality MetamethodsRecap: Dispatch ReportsPractice on your own: Online Lua compiler