Collection of interfaces

Interfaces

-- No interface to declare: any object that has
-- a get_name method fits, no common parent
local Flower = {}
Flower.__index = Flower

function Flower.new(name)
  return setmetatable({name = name}, Flower)
end

function Flower:get_name()
  return self.name
end

local City = {}
City.__index = City

function City.new(name)
  return setmetatable({title = name}, City)
end

function City:get_name()
  return self.title
end

-- A plain table with a function fits too
local sirius = {get_name = function()
  return "Sirius"
end}

local rows = {Flower.new("Rose"),
              City.new("Rome"), sirius}
local names = {}
for _, row in ipairs(rows) do
  names[#names + 1] = row:get_name()
end
-- names = Rose, Rome, Sirius

print("names = " .. table.concat(names, ", "))

-- Nothing is checked until the call
local rock = {}
local ok, err = pcall(function()
  return rock:get_name()
end)
-- ok = false
-- err = main.lua:43: attempt to call a nil value
-- (method 'get_name')
print("ok = " .. tostring(ok))
print("err = " .. err)