Lua面向对象的实现方法

Lua实现面向对象方法大概整理了一些,分为以下两种方法:

方法一:

官方做法:

实现类:

    local Class= { value=0 }

    function  Class:new(o)
         o=o or {};
         setmetatable(o,self);
         self.__index=self;
         return o;
    end

    function  Class:showmsg()
        print(self.value);
    end

    local  test = Class:new();
    test:showmsg();

接着上面实现继承

    local  A = Class:new();

    function  A:new(o)
          local  o = o or {};
          setmetatable(o,self);
          self.__index=self;
          return o;
    end
    function  A:showmsg(  )
        print (self.value);
        print("zhishi 测试啊啊 ")
    end

    local  s = A:new({value=100});
    s:showmsg();

结果:

0
100
zhishi 测试啊啊 

方法二

一种更优雅的实现方式:

class.lua 代码:


local _class={}

function class(super)
    local class_type={}
    class_type.ctor=false
    class_type.super=super
    class_type.new=function(...) 
            local obj={}
            do
                local create
                create = function(c,...)
                    if c.super then
                        create(c.super,...)
                    end
                    if c.ctor then
                        c.ctor(obj,...)
                    end
                end

                create(class_type,...)
            end
            setmetatable(obj,{ __index=_class[class_type] })
            return obj
        end
    local vtbl={}
    _class[class_type]=vtbl

    setmetatable(class_type,{__newindex=
        function(t,k,v)
            vtbl[k]=v
        end
    })

    if super then
        setmetatable(vtbl,{__index=
            function(t,k)
                local ret=_class[super][k]
                vtbl[k]=ret
                return ret
            end
        })
    end

    return class_type
end

下面看下使用:

定义一个类:

test=class()       -- 定义一个基类 base_type
function test:ctor(x)  -- 定义 base_type 的构造函数

    print("test ctor")

    self.x=x

end
function test:print_x()    -- 定义一个成员函数 test:print_x

    print(self.x)

end
function test:hello()  -- 定义另一个成员函数 test:hello

    print("hello test")

end


--调用方法

test.new(1);
test:print_x();
test:hello();

继承的实现:

base=class()       -- 定义一个基类 base_type
function base:ctor(x)  -- 定义 base_type 的构造函数

    print("base ctor")

    self.x=x

end
function base:print_x()    -- 定义一个成员函数 base:print_x

    print(self.x)

end
function base:hello()  -- 定义另一个成员函数 base:hello

    print("hello base")

end



--子类实现
child=class(base);
function child:ctor()
    print("child ctor");
end

function child:hello()
     print("hello child")
end


--调用
 local a=child.new(21);
 a:print_x();
 a:hello();

两种方式各有优缺点,看自己了,不明白的地方留言交流。。。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值