-- 元类
local classA= {area = 0, length = 0, breadth = 0}
-- 创建实例化对象方法 new
function classA:new (length,breadth)
local o = {}
self.__index = self --调用table的一个不存在的索引时,会使用到元表的__index元方法
setmetatable(o, self) --classA作为o的元类,即o有classA的所有属性和方法
o.length = length
o.breadth = breadth
return o --返回一个实例对象
end
--输出面积方法 printArea
function classA:printArea ()
self.area = self.length*self.breadth;
print("矩形面积为 ",self.area)
end
A = classA:new(10,20)
B = classA:new(3,3)
A:printArea()
B:printArea()
A.length = 2
A:printArea()
输出结果