Polymorphism by Protocol
Lesson 27 of 35 in Coddy's Luau for Lua Developers course.
Lua duck typing transfers, with optional structural descriptions for Luau analysis. A :: assertion does not supply any missing operation, so runtime protocols remain observable behavior.
Lua 5.1 comparison
local email={send=function(self,text) return "email:"..text end}
local sms={send=function(self,text) return "sms:"..text end}
local out={}
for _,c in ipairs({email,sms}) do out[#out+1]=c:send("hi") end
print(table.concat(out,"|"))Luau behavior
A protocol is a set of callable operations. Luau structural types can describe a renderer, while runtime code simply invokes the method. Test multiple independent implementations. A type assertion using :: informs analysis; it does not add missing methods to an object.
local email={send=function(self,text) return "email:"..text end}
local sms={send=function(self,text) return "sms:"..text end}
local out={}
for _,c in ipairs({email,sms}) do out[#out+1]=c:send("hi") end
print(table.concat(out,"|"))Expected Luau output:
email:hi|sms:hiChallenge
EasyInput is a message line. Implement email.luau and sms.luau, 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.luau, email.luau, sms.luau. The visible locked main.luau 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 Luau for Lua Developers
4Functions and Closures
Functions and ReturnsDefaults and Options TablesMultiple Results and VarargsCallbacks and Captured StateRecap: Pricing Functions7Objects and Owned State
Tables as Instancesself and Colon CallsIndependent Instance TablesRecap: Account Objects5Tables as Collections
Lists as Dense TablesDictionaries and pairsAliasing and Shallow CopiesRecap: Count Inventory8Composition and Object Lookup
Composition and DelegationPrototype Lookup ChainsPolymorphism by ProtocolValue Equality MetamethodsRecap: Dispatch ReportsPractice on your own: Online Luau compiler