《Lua 程序设计》-16.3多重继承

-- look up for `k' in list of tables 'plist'

local function search (k, plist)

    for i=1, table.getn(plist) do

       local v = plist[i][k]    -- try 'i'-th superclass

       if v then return v end

    end

end

 

function createClass (...)

    local c = {}      -- new class

 

    -- class will search for each method in the list of its

    -- parents (`arg' is the list of parents)

    setmetatable(c, {__index = function (t, k)

 
    
        return search(k, arg)
    
    end})

 

    -- prepare `c' to be the metatable of its instances
    
    c.__index = c

 

    -- define a new constructor for this new class
    
    function c:new (o)
    
        o = o or {}
    
        setmetatable(o, c)
    
        return o

    end

 

    -- return new class
    
    return c

end

   Named = {}

      function Named:getname ()
      
          return self.name
      
      end
      
       
      
      function Named:setname (n)
      
          self.name = n
      
      end
      
      
      
      Account = {balance = 0}

       
      
      function Account:new (o)
      
          o = o or {}
      
          setmetatable(o, 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 error"insufficient funds" end
      
          self.balance = self.balance - v
      
      end
       
      NamedAccount = createClass(Account, Named)     
      
      account = NamedAccount:new{name = "Paul"}

      print(account:getname())    --> Paul


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值