1.基于元表进行使用
原理:当设置了元表,并且设置了元表的__index,当前表没有的属性会根据__index指向的表进行寻找
2.new的过程:返回一张空表,并且设置元表为调用new方法的表
3.inherit的过程:往_G表(存储所有全局变量的表),写入一张表,并且设置元表为调用inherit
要注意的点是:重写父类方法,如果要调用父类的方法,在添加新的功能时,调用父类的方法要使用.调用
--封装
Object={}
Object.posx=0
Object.posy=0
--new 实例化
function Object:new( )
local obj={}
setmetatable(obj,self)
self.__index=self
return obj
end
local o1=Object:new()
print(o1.posx)
print(o1.posy)
--inherit 继承
function Object:inherit(className)
_G[className]={}
local obj = _G[className]
setmetatable(obj,self)
self.base=self
return obj
end
Object:inherit("PlayerObject")
p1=PlayerObject:new()
function PlayerObject:Move( )
self.posx=self.posx+1
self.posy=self.posy+1
end
p1.Move(p1)
print(p1.posx)
print(p1.posy)
PlayerObject:inherit("MyPlayerObject")
function MyPlayerObject:Move( )
--使用.调用父类的方法,而不适用:调用,因为使用:调用,会把元表playerObject当成self使用,而不是当前的调用者
self.base.Move(self)
print(self.posx)
print(self.posy)
end
print("---")
mypo1=MyPlayerObject:new()
mypo1:Move()
mypo2=MyPlayerObject:new()
mypo2:Move()