zoukankan      html  css  js  c++  java
  • lua类实现

    _Account = {}
    
    --创建一张借记卡
    function _Account:new( tb )
        local _Tb = tb or {}
        _Tb._mBalance = _Tb._mBalance or 0
        setmetatable(_Tb, self)
        self.__index = self
        return _Tb
    end
    
    --借记卡取款
    function _Account:desposit( value )
        if value > self._mBalance then
            print(string.format("取款"..value .. "失败, 剩余存款" .. self._mBalance))
            return
        end
        self._mBalance = self._mBalance - value
        print(string.format("取款"..value .. ", 剩余存款" .. self._mBalance))
    end
    
    --存钱
    function _Account:addBalance(val)
        local num = val or 0
        self._mBalance = self._mBalance + num
        print("存钱"..val)
    end
    
    --[[
        信用卡也具备储蓄卡的存取功能,所以直接继承储蓄卡,复用储蓄卡的存钱功能。
    
        我们在访问一个表不存在的域时,lua解释器会去查找metatable中是否有__index方法(metamethod),如果不存在则返回nil。
        _Credit是_Account:new出来的,metatable是_Account,__index也是_Account,所以当_Credit对象访问addBalance的时候,
        会到_Account中找。
    ]]
    
    _Credit = _Account:new({_mLimit = 1000})
    
    --信用卡取款
    function _Credit:desposit( value )
        if value > self._mBalance + self._mLimit then
            print(string.format("取款"..value .. "失败, 剩余额度" .. self._mLimit .. ", 剩余存款"..self._mBalance))
            return
        end
    
        if self._mBalance >= value then
            self._mBalance = self._mBalance - value
        else
            self._mLimit = self._mLimit - (value - self._mBalance)
            self._mBalance = 0
        end
    
        print(string.format("取款"..value .. ", 剩余额度" .. self._mLimit .. ", 剩余存款"..self._mBalance))
    end
    
    print("          --储蓄卡--")
    local myAccount_2 = _Account:new()
    myAccount_2:addBalance(1000)
    myAccount_2:desposit(200)
    myAccount_2:desposit(2000)
    
    print("
              --信用卡--")
    local cyCredit = _Credit:new()
    cyCredit:addBalance(600)
    cyCredit:desposit(500)
    cyCredit:desposit(500)
    cyCredit:desposit(1000)
    
    --[[结果
    
              --储蓄卡--
    存钱1000
    取款200, 剩余存款800
    取款2000失败, 剩余存款800
    
              --信用卡--
    存钱600
    取款500, 剩余额度1000, 剩余存款100
    取款500, 剩余额度600, 剩余存款0
    取款1000失败, 剩余额度600, 剩余存款0
    
    ]]
  • 相关阅读:
    SpringBoot优雅的全局异常处理
    react格式化展示json
    Pycharm调试按钮
    HttpURLConnection和okhttp的使用
    objection自动生成hook代码
    hookString
    python取中位数 位运算
    scrapy mongo pipeline
    xpath tips
    IT日语
  • 原文地址:https://www.cnblogs.com/wrbxdj/p/5379897.html
Copyright © 2011-2022 走看看