一天三盒半 发表于 昨天 15:17

LUA进阶教程——Lua 面向对象(Table + Metatable 模拟)

最简类实现(: 语法糖)

-- 类
local Person = {}
Person.__index = Person

-- 构造函数
function Person:new(name, age)
    local obj = {name=name, age=age}
    setmetatable(obj, self) -- self 是 Person
    return obj
end

-- 方法
function Person:sayHi()
    print("Hi, I'm "..self.name..", age "..self.age)
end

-- 对象
local p = Person:new("Tom", 20)
p:sayHi() -- Hi, I'm Tom, age 20继承
-- 子类 Student 继承 Person
local Student = setmetatable({}, {__index=Person})
Student.__index = Student

function Student:new(name, age, score)
    local obj = Person:new(name, age) -- 父类构造
    obj.score = score
    setmetatable(obj, self)
    return obj
end

function Student:showScore()
    print(self.name.." score: "..self.score)
end

local s = Student:new("Alice", 18, 90)
s:sayHi()    -- 继承父类方法
s:showScore()

页: [1]
查看完整版本: LUA进阶教程——Lua 面向对象(Table + Metatable 模拟)