Lua面向对象的实现方法

来源:互联网 发布:阿里云独立ip主机 编辑:程序博客网 时间:2024/06/06 00:45

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();

结果:

0100zhishi 测试啊啊 

方法二

一种更优雅的实现方式:

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_typeend

下面看下使用:

定义一个类:

test=class()       -- 定义一个基类 base_typefunction test:ctor(x)  -- 定义 base_type 的构造函数    print("test ctor")    self.x=xendfunction test:print_x()    -- 定义一个成员函数 test:print_x    print(self.x)endfunction test:hello()  -- 定义另一个成员函数 test:hello    print("hello test")end--调用方法test.new(1);test:print_x();test:hello();

继承的实现:

base=class()       -- 定义一个基类 base_typefunction base:ctor(x)  -- 定义 base_type 的构造函数    print("base ctor")    self.x=xendfunction base:print_x()    -- 定义一个成员函数 base:print_x    print(self.x)endfunction base:hello()  -- 定义另一个成员函数 base:hello    print("hello base")end--子类实现child=class(base);function child:ctor()    print("child ctor");endfunction child:hello()     print("hello child")end--调用 local a=child.new(21); a:print_x(); a:hello();

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

0 0
原创粉丝点击