lua的class简易实现

直接贴代码:

function class(classname, super)
    local superType=type(super)
    local cls

    if superType ~= "function" and superType ~= "table" then
        superType=nil
        super=nil
    end

    if super then
        cls={}
        setmetatable(cls, {__index=super})
        cls.super=super
    else
        cls={ctor=function() end}
    end

    cls.__cname=classname
    cls.__index=cls

    function cls.new(...)
        local instance=setmetatable({}, cls)
        instance.class=cls
        instance:ctor(...)
        return instance
    end

    return cls

end

-- 定义名为 Shape 的基础类  
local Shape = class("Shape")
-- ctor() 是类的构造函数,在调用 Shape.new() 创建 Shape 对象实例时会自动执行  
function Shape:ctor(shapeName) 
    self.shapeName = shapeName  
    print(string.format("Shape:ctor(%s)", self.shapeName))  
end
-- 为 Shape 定义个名为 draw() 的方法  
function Shape:draw()
    print(string.format("draw %s", self.shapeName))  
end

-- Circle 是 Shape 的继承类  
local Circle = class("Circle", Shape)
function Circle:ctor()  
    -- 如果继承类覆盖了 ctor() 构造函数,那么必须手动调用父类构造函数  
    -- 类名.super 可以访问指定类的父类  
    Circle.super:ctor("circle")  
    self.radius = 100  
end   
function Circle:setRadius(radius)  
    self.radius = radius  
end
-- 覆盖父类的同名方法  
function Circle:draw()  
    print(string.format("draw %s, radius = %0.2f", self.shapeName, self.radius))
end

local circle1=Circle.new()
circle1:setRadius(125)
circle1:draw()

 

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值