lua面向对象例子

来源:互联网 发布:超市行业数据 编辑:程序博客网 时间:2024/05/03 23:50
#!/usr/bin/lua-- 对象A,也是一个类型(对象与类是一个东西,称之为原型)A ={    x = 10,    y = 20}function A:new(o)    o = o or {} -- create object if user does not provide one    setmetatable(o, self)    self.__index = self    return oendfunction new(o)    A:new(o)endfunction A:acc(v)    self.x = self.x + vendfunction A:dec(v)    if v > self.x then    error "not more than zero"    end    self.x = self.x - vend--从A中产生一个对象AA,也是子类型AA = A:new()-- 重载function AA:acc(v)    self.x = self.x + v    print(self.x)end-- 子类中新增的方法function AA:getx()    return self.xend--此时,AA就是一个新表了,它是一个对象,但也是一个类,是AA的子类。它还可以继续如下操作:s = AA:new()--然后,现在调用s:acc(5)s:dec(10)print(s:getx())
原创粉丝点击