Intro
Lua的对象的本质其实依然是一张表
Class
Lua没有类的概念,但是可以参考基于原型的语言(prototype-based language)来模拟类
setmetatable(A, {__index = B}) 即可完成类B的对象A的创建Account = { balance = 0, withdraw = function(self, v) if (v > self.balance) then error "insufficient funds" end self.balance = self.balance - v end, __tostring = function (acc) return ("Balance: " .. acc.balance) end, -- __index = Account, } function Account:deposit (v) self.balance = self.balance + v end function Account:new (o) o = o or {} -- 若创建时o为nil则自动创建一个空表 self.__index = self setmetatable(o, self) return o end local a = Account:new() a:deposit(100) print(a)
Inheritance
直接在新建的对象中创建新字段 / 覆盖原有方法的字段
注意:元方法字段无法被继承,需要自己在子类中显式重写
补充:另一种实现方式是直接设置新的类的metatable为要继承的类,__index设置为自己即可
SpecialAccount = Account:new({ limit = 1000.00, __tostring = Account.__tostring }) -- override 'new', but not necessary function SpecialAccount:new(o) o = Account:new(o) self.__index = self setmetatable(o, self) return o end s = SpecialAccount:new() function SpecialAccount:withdraw (v) if (v - self.balance > self:getlimit()) then error "insufficient funds : out of limit" end self.balance = self.balance - v end function SpecialAccount:getlimit () return self.limit or 0 end s:withdraw(100) s:deposit(500) print(s) -- Balance: 400 local DerivedSpecialAccount = SpecialAccount:new({limit = 2000, __tostring = SpecialAccount.__tostring}) local dsa = DerivedSpecialAccount:new() dsa:withdraw(1050) dsa:deposit(100) print(dsa)
Multiple Inheritance
将其他类的方法组合到子类,勉强实现一下多重继承