一天三盒半 发表于 2026-5-27 14:14:42

Lua 高级教程——Lua 面向对象(基于元表实现)

Lua 无原生 class,用元表 +__index+self 模拟类、继承、多态。

1. 类与对象
-- 定义类
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



页: [1]
查看完整版本: Lua 高级教程——Lua 面向对象(基于元表实现)