Use a Shared Method Protocol
Lesson 40 of 48 in Coddy's Lua for C Developers course.
C can describe interchangeable behaviors with a struct containing a callback and its associated data. The compiler checks the callback signature, and the caller follows the interface convention. Lua can accept unrelated tables that provide the same method name and receiver convention. No common prototype is required. The notification loop below uses only send and the message; it does not inspect a channel type. This keeps the loop independent of how each channel constructs its response.
C
#include <stdio.h>
#include <stddef.h>
struct Channel {
const char *prefix;
void (*send)(const struct Channel *self, const char *text);
};
static void send_prefixed(const struct Channel *self, const char *text)
{
printf("%s:%s", self->prefix, text);
}
int main(void)
{
struct Channel channels[] = {
{"email", send_prefixed}, {"sms", send_prefixed}
};
for (size_t i = 0; i < 2; ++i) {
if (i != 0) {
putchar('|');
}
channels[i].send(&channels[i], "hi");
}
putchar('\n');
return 0;
}Lua
local email = {prefix = "email"}
function email:send(text)
return self.prefix .. ":" .. text
end
local sms = {prefix = "sms"}
function sms:send(text)
return self.prefix .. ":" .. text
end
local out = {}
for _, channel in ipairs({email, sms}) do
out[#out + 1] = channel:send("hi")
end
print(table.concat(out, "|"))Porting trap
Lua checks method availability at the call site. A missing send field fails when called; an incompatible receiver convention can fail or produce incorrect results at runtime. Document that implementations accept self and text, return a string, and handle an empty message; exercise each implementation through that protocol.
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 C Developers
1First Lua Programs
Run Lua ModulesPrint and CommentNames and Local ScopeNumbers and ConversionStrings and Byte PositionsRecap: Format a Receipt4Functions and Closures
Functions and ArgumentsDefaults and Options TablesMultiple Results and VarargsCallbacks and Captured StateRecap: Pricing Functions2Values and Decisions
Absence and Table FieldsTruth and Default ValuesBranches and BoundsValues and Table IdentityRecap: Admission Rules5Tables as Collections
Arrays to Dense TablesRecords and Dynamic KeysSets and MembershipAliasing and Shallow CopiesRecap: Count Inventory8Composition and Object Lookup
Customize String ConversionDelegate to a CollaboratorBuild Prototype Lookup ChainsUse a Shared Method ProtocolCompare Values with __eqRecap: Dispatch ReportsPractice on your own: Online Lua compiler