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

  • 相关阅读:
    SQL 脚本 重复执行 约束
    xiami 精选集
    PHP 5 环境配置
    Thread线程类
    创建线程
    C#中简单的正则表达式(也经常会用到的)
    线程的挂起与恢复
    C#操作INI文件
    多线程简介
    单线程简介
  • 原文地址:https://www.cnblogs.com/byfei/p/3112349.html
Copyright © 2011-2022 走看看