美文网首页
Lua脚本中实现Class机制

Lua脚本中实现Class机制

作者: 左脚迈太快 | 来源:发表于2019-11-08 20:59 被阅读0次
    function class(super)
        local class_type = {}
        class_type.ctor = false
        class_type.super = super
        class_type.delete = function(t)
            t.__safe_shield = nil
            do
                local del
                del = function(c)
                    local dtor = rawget(c, 'dtor')
                    if dtor then
                        dtor(t)
                    end
                    if c.super then
                        del(c.super)
                    end
                end
                del(class_type)
            end
        end
        class_type.new = function(...)
            local obj = setmetatable({}, { __index = class_type })
            obj.__safe_shield=true
            do
                local create
                create = function(c, ...)
                    if c.super then
                        create(c.super, ...)
                    end
                    local ctor = rawget(c, 'ctor')
                    if ctor then
                        ctor(obj, ...)
                    end
                end
                create(class_type, ...)
            end
            return obj
        end
        if super then
            setmetatable(class_type, { __index = function(t,k)
                local ret = class_type.super[k]
                class_type[k] = ret
                return ret
            end
            })
        end
        return class_type
    end
    
    base_type=class()       -- 定义一个基类 base_type
     
    function base_type:ctor(x)  -- 定义 base_type 的构造函数
        print("base_type ctor")
        self.x=x
    end
    
    function base_type:dtor()
        print("base_type dtor")
    end
     
    function base_type:print_x()    -- 定义一个成员函数 base_type:print_x
        print(self.x)
    end
     
    function base_type:hello()  -- 定义另一个成员函数 base_type:hello
        print("hello base_type")
        self:print_x()
    end
    
    test=class(base_type)   -- 定义一个类 test 继承于 base_type
     
    function test:ctor()    -- 定义 test 的构造函数
        print("test ctor")
    end
    
    function test:dtor()
        print("test dtor")
    end
    
    function test:print_x()
        print("test print_x")
    end
     
    -- function test:hello()    -- 重载 base_type:hello 为 test:hello
    --  print("hello test")
    -- end
    
    a=test.new(1)   -- 输出两行,base_type ctor 和 test ctor 。这个对象被正确的构造了。
    a:hello()   -- 输出 1 ,这个是基类 base_type 中的成员函数。
    a:delete()
    

    纯lua脚本实现c++中的类的概念机制,后面空了把lua和c++的交互,lua中直接声明和使用c++中定义的对象补充到这个系列上

    相关文章

      网友评论

          本文标题:Lua脚本中实现Class机制

          本文链接:https://www.haomeiwen.com/subject/jmgwbctx.html