Menu
CoddyTech

Use a Shared Method Protocol

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

Go interface satisfaction is implicit from the method set, with pointer and value receivers affecting which types satisfy it. Lua consumers likewise call a behavioral protocol, but no static interface check guarantees those methods exist. Every table must provide the required function and agree on self passing. Test each implementation independently.

Go

package main
import ("fmt"; "strings")
type Channel interface{Send(string)string}
type Email struct{}
func(Email) Send(s string)string{return "email:"+s}
type Sms struct{}
func(Sms) Send(s string)string{return "sms:"+s}
func main(){
channels:=[]Channel{Email{},Sms{}}; out:=[]string{}; for _,c:=range channels {out=append(out,c.Send("hi"))}; fmt.Println(strings.Join(out,"|"))
}

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

Provide the expected callable method on every Lua channel.

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 Go Developers

Practice on your own: Online Lua compiler