-- 定义类
local Person = {}
Person.__index = Person -- 元表指向自身
-- 构造函数
function Person.new(name, age)
local self = setmetatable({}, Person)
self.name = name
self.age = age
return self
end
-- 方法
function Person:sayHello()
print(string.format("我是 %s,%d 岁", self.name, self.age))
end
-- 创建对象
local p = Person.new("张三", 20)
p:sayHello() -- 我是 张三,20 岁
2. 继承
-- 子类 Student,继承 Person
local Student = setmetatable({}, {__index=Person})
Student.__index = Student
-- 子类构造
function Student.new(name, age, score)
local self = Person.new(name, age) -- 调用父类构造
setmetatable(self, Student)
self.score = score
return self
end
-- 子类重写方法
function Student:sayHello()
print(string.format("学生 %s,%d 岁,分数 %d", self.name, self.age, self.score))
end
local s = Student.new("李四", 18, 90)
s:sayHello() -- 学生 李四,18 岁,分数 90