lua의class 간이 실현

1504 단어 language
코드에 직접 부착:
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()

좋은 웹페이지 즐겨찾기