zoukankan      html  css  js  c++  java
  • 在看lua仿单继承

    --lua仿单继承
    Account = { balance = 0}
    --对于成员变量,第一此访问要使用元表中的,在第一次也赋值到自己的域中了
    --将不涉及到__index了
    function Account:new(o)
      o = o or {}
      
     --setmetatable看到后面,忘了这个啥意思了
     --如a+b,当lua试图对两个表进行相加时,他会检查两个表是否有一个表有metatable,
     --如果知道检查到元表有__add域,如果有直接调用__add方法
      setmetatable(o, self)--Account表本身作为o的metatable,不设置元表,他到哪儿去查找元方法呢
      
      --当调用self没有的成员时到self里面查找
      self.__index = self--自己作为自己的原型
      return o
    end
    
    function Account:deposit(v)
      self.balance = self.balance + v
    end
    
    function Account:withdraw(v)
      if v > self.balance then print("insufficient funds") end
      self.balance = self.balance - v
    end
    
    SpecialAccount = Account:new()--从Account继承所有操作
    
    --重定义父类的withdraw函数因为他在本对象中就找到了此方法
    function SpecialAccount:withdraw(v)
      if v - self.balance >= self:getLimit() then
        print("insufficient funds")
      end
      self.balance = self.balance - v
    end
    
    function SpecialAccount:getLimit()
      return self.limit or 0
    end
    
    SpecialAccount = Account:new()--SpecialAccount此时将Account设置成了元表,SpecialAccount有了Account的所有的成员
    --此时SpecialAccount的域limit的值已经是1000
    s = SpecialAccount:new{limit = 1000.00}--s继承SpecialAccount有SpecialAccount所有的成员,SpecialAccount继承Account
    s:withdraw(200.00)
    s:deposit(100.00)

    吗的真不好理解,太绕了

  • 相关阅读:
    MFC Picture Ctrl 无失真自适应显示图片
    肖申克的救赎
    iOS开发常用工具
    代码管理工具 --- git的学习笔记四《重新整理git(1)》
    压缩与解压缩
    读书笔记——金融学-投资哪些事(职业投资人),读报
    读书笔记——金融学-《国富论》
    文件下载 NSURLConnection——文件下载与上传
    视频播放一
    XML解析
  • 原文地址:https://www.cnblogs.com/zzyoucan/p/4331140.html
Copyright © 2011-2022 走看看