示例工程 18-inheritance-and-mixins

18-inheritance-and-mixins/03-mixin-compose/main.lua

lua · 0.9 KB

-- @runtimes lua54 luajit
--- 演示:把多个表的方法复制进类表。
local M = {}
 
local function mixin(target, source)
	for key, value in pairs(source) do
		if target[key] == nil then
			target[key] = value
		end
	end
	return target
end
 
local Loggable = {
	log = function(self, msg)
		return self.name .. ":" .. msg
	end,
}
local Timestamped = {
	stamp = function(self)
		return self.name .. "@now"
	end,
}
 
local Service = { name = "svc" }
mixin(Service, Loggable)
mixin(Service, Timestamped)
function Service:run()
	return self:log("run")
end
 
--- @return table { logged = string, stamped = string }
function M.run(log)
	log = log or print
	local service = setmetatable({ name = "svc" }, { __index = Service })
	local logged = service:run()
	local stamped = service:stamp()
	log(("logged=%s stamped=%s"):format(logged, stamped))
	return { logged = logged, stamped = stamped }
end
 
if not ... then
	M.run()
end
return M