Menu
CoddyTech

Polymorphism by Protocol

Lesson 40 of 48 in Coddy's Lua for PHP Developers course.

PHP interfaces let classes declare a shared method contract, and parameter types can require that interface. Lua tables need no shared declaration to support the same call. A notification loop can call send on each table as long as every implementation follows the agreed receiver and argument convention. The language does not validate an interface at construction time. Test each module's public behavior, including empty input, so a missing method is discovered before a larger application relies on it.

PHP

<?php
interface Channel { public function send(string $text): string; }
class Email implements Channel {
    public function send(string $text): string { return "email:" . $text; }
}
class Sms implements Channel {
    public function send(string $text): string { return "sms:" . $text; }
}
$out = [];
foreach ([new Email(), new Sms()] as $c) { $out[] = $c->send("hi"); }
echo implode("|", $out), "\n";

Lua

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

Removing a PHP interface declaration does not remove the need for a contract. Document the Lua method names, arguments, returns, and mutation behavior. Keep the colon convention consistent across all implementations.

challenge icon

Challenge

Easy

Input 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))
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Lua for PHP Developers

Practice on your own: Online Lua compiler