zoukankan      html  css  js  c++  java
  • lua的继承2

    Account = {balance = 0}
    function Account:new (o)
        o = o or {}
        setmetatable(o, self)
        self.__index = self
    	print("This is Base")
        return o
    end
    
    function Account:deposit (v)
        self.balance = self.balance + v
    end
    
    function Account:withdraw (v)
        if v > self.balance then
    		error"insufficient funds"
    	end
        self.balance = self.balance - v
    end
    
    SpecialAccount = Account:new()
    
    function SpecialAccount:withdraw (v)
        if v - self.balance >= self:getLimit() then
           print("error insufficient funds")
    	   return -1
        end
        self.balance = self.balance - v
    end
    
    function SpecialAccount:getLimit ()
        return self.limit or 0
    end
    
    
    s = SpecialAccount:new{limit=1000.00}
    --在Lua中面向对象有趣的一个方面是你不需要创建一个新类去指定一个新的行为.
    --如果仅仅一个对象需要特殊的行为,你可以直接在对象中实现
    function s:getLimit ()
        return self.balance * 0.10
    end
    
    s:deposit(100.00)	--调用基类的存钱函数
    print(s.balance)
    s:withdraw(200.00)	--调用子类的取钱函数,取钱失败
    print(s.balance)
    s:getLimit()		--调用了s:getLimit ()
    print(s.limit)
    


     

    原文:

    http://book.luaer.cn/_98.htm

  • 相关阅读:
    ios 读取通讯录
    隐藏多余的分割线
    Cell高亮时设置cell内容
    iOS录音
    iOS发送信息功能(生成信息内容)
    iOS颜色选择器
    iOS缓存
    二维码扫描
    梵讯笔记
    微信开发后台库
  • 原文地址:https://www.cnblogs.com/byfei/p/3112349.html
Copyright © 2011-2022 走看看