Polymorphism by Protocol
Lesson 40 of 48 in Coddy's Lua for Rust Developers course.
Rust traits require explicit implementations and support generic bounds or trait-object dispatch. Lua consumers call a method protocol directly from tables without static trait checking. Every implementation must agree on receiver passing, arguments and result. A shared base table is optional when unrelated objects already provide compatible behavior.
Rust 2021
Rust declarations:
trait Channel{fn send(&self,text:&str)->String;}
struct Email; impl Channel for Email{fn send(&self,text:&str)->String{format!("email:{}",text)}}
struct Sms; impl Channel for Sms{fn send(&self,text:&str)->String{format!("sms:{}",text)}}Rust entry point:
fn main() {
let email=Email; let sms=Sms; let channels:[&dyn Channel;2]=[&email,&sms]; let out:Vec<_>=channels.iter().map(|c|c.send("hi")).collect(); println!("{}",out.join("|"));
}Lua 5.1
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,"|"))Porting trap
Document and test the callable protocol at each Lua boundary.
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 Rust 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 Options TablesMultiple Results and VarargsCallbacks and Captured StateRecap: Pricing Functions2Values and Decisions
Absence and Missing FieldsTruth and Default ValuesBranches and BoundsEquality and IdentityRecap: Admission Rules5Tables as Collections
Vectors as Dense TablesMaps 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