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


--基类people
local people = class();
--构造函数
function people:ctor(sex,age)
       print("people new .........");
       self.sex = sex;
       self.age = age;
end
--成员函数
function people:show()
       print("people show .............");
       print("sex: ",self.sex," age: ",self.age);
end
--成员函数
function people:speek()
      print("people speek ...........");
end

--派生类boy 继承至 people
local boy = class(people);
function boy:ctor(sex,age,tag)
     print("boy new .............");
     self.tag = tag;
end
--派生类重写基类方法
function boy:show()
     print("boy show ...................");
     print("sex: ",self.sex," age: ",self.age," tag: ",self.tag);
end

-----------测试代码

--实例化类boy
peo1 = boy.new("Rain","25","1");
--调用自己重写的方法
peo1:show();
--调用基类方法
peo1:speek();
print("-------------------------")
peo2 = boy.new("second","10","2");
peo2:show();
peo2:speek();
print("-------------------------")
peo1:show();
peo1:speek();

print("***********************");

可以直接在lua编译器调试。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值