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)
原文: