x-- 基类
Person = {}
-- 基类中的方法
function Person:say()
print(string.format("I am %s, %d years old.", self.name, self.age))
end
-- 子类
Student = {}
-- 为子类设置元表。不允许获取和设置子类的元表,防止继承结构被破坏
setmetatable(Student, { __index = Person, __metatable = "permission denied" })
-- 子类的构造方法
function Student:new(name, age, grade)
return setmetatable({ name = name or "", age = age or 0, grade = grade or 1 }, {
__index = self,
-- 不允许获取和设置对象的元表,防止继承结构被破坏
__metatable = "permission denied" })
end
function Student:study()
print(string.format("I am studying %d grade courses", self.grade))
end
Teacher = {}
setmetatable(Teacher, { __index = Person, __metatable = "permission denied" })
function Teacher:new(name, age, grade)
return setmetatable(
{ name = name or "", age = age or 0, grade = grade or 1 },
{ __index = self, __metatable = "permission denied" }
)
end
function Teacher:teach()
print(string.format("I am teaching %d grade courses", self.grade))
end
s = Student:new("Gloria", 8, 1)
s:say()
s:study()
t = Teacher:new("Tim", 30, 2)
t:say()
t:teach()
输出:
xxxxxxxxxx
I am Gloria, 8 years old.
I am studying 1 grade courses
I am Tim, 30 years old.
I am teaching 2 grade courses