示例工程 18-inheritance-and-mixins

18-inheritance-and-mixins/02-super-call/main.lua

lua · 0.7 KB

-- @runtimes lua54 luajit
--- 演示:用父类方法显式调用实现 super。
local M = {}
 
local Base = {}
Base.__index = Base
function Base.new()
	return setmetatable({}, Base)
end
function Base:greet()
	return "base"
end
 
local Child = setmetatable({}, { __index = Base })
Child.__index = Child
function Child.new()
	return setmetatable({}, Child)
end
function Child:greet()
	return "child+" .. Base.greet(self)
end
 
--- @return table { base = string, child = string }
function M.run(log)
	log = log or print
	local base = Base.new():greet()
	local child = Child.new():greet()
	log(("base=%s child=%s"):format(base, child))
	return { base = base, child = child }
end
 
if not ... then
	M.run()
end
return M