• 在看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)

    吗的真不好理解,太绕了

  • 相关阅读:
    Python 环境安装教程(Windows 10)
    去掉页面状态栏的方法
    iOS开发init方法解析
    xCode删除storyboard,新建window并启动
    应用程序代理AppDelegate解析
    nib文件的注册及加载
    cocospods的安装与应用
    Objective-C 理解之方括号[ ]的使用
    36辆自动赛车和6条跑道的问题
    编程珠玑第二章
  • 原文地址:https://www.cnblogs.com/zzyoucan/p/4331140.html
Copyright © 2020-2023  润新知