Lua 使用metatable和元方法实现面向对象编程中的封装,继承,多态

local function class(name, parent)
	local tempClass = {}
	parent = parent and parent or {}

	--实现元方法
		parent.__index = function(table, key)
		return parent[key]
	end

	setmetatable(tempClass, parent)
	tempClass.__name = name
	tempClass.__super = parent
	return tempClass
end

local function dump(value, dumpChild)
	for k, v in pairs(value) do
		local t = type(v)
		if t == "function" then
			print(k..":function")
		elseif t == "table" then
			print(k..":table")
			if dumpChild then
				print("{")
				dump(v)
				print("}")
			end
		else
			print(k..":"..v)
		end	

	end
end

local classParent = class("parent", nil)


function classParent:ParentFunction()
	print("This is ParentFunction")
end

local classChild = class("Child", classParent)


--实现Override
function classChild:ParentFunction()
	self.__super:ParentFunction()
	print("This is ChildFunction")
end


classChild:ParentFunction()

猜你喜欢

转载自blog.csdn.net/qq_29094161/article/details/82838172