1.原理 运用元表,和元表的__index,与new不同的是,作为元表的子表,在直接写到_G表中作为全局表。 本质上是有无写到_G表中,并且如果使用继承的形式,在声明一个实例,当没有给变量赋值的时候,根据__index的嵌套原理,访问的是父类中的属性(newClassInstance->通过元表__index=NewClass找到NewClass->NewClass通过元表__index=Object找到Object)。 表现为作为实例化的表,用作变量使用,作为继承的表,当作声明表的变量使用
Object
={}
Object
.id
=1
print("--new--")
function Object
:new( )
local instance
={}
setmetatable(instance
,self
)
self
.__index
=self
return instance
end
local myInstance
=Object
:new()
print(myInstance
.id
)
print("--inherit--")
function Object
:inherit( className
)
_G
[className
]={}
local newClass
=_G
[className
]
setmetatable(newClass
,self
)
self
.__index
=self
end
Object
:inherit("Newclass")
local newClassInstance
=Newclass
:new()
print(newClassInstance
.id
)