Account={balance=0} function Account.withdraw(self,v) self.balance=self.balance-v end a={balance=0,withdraw=Account.withdraw} a.withdraw(a,260) --面向对象语言常使用self参数,lua提供了通过使用冒号操作符来隐藏self参数的声明 function Account:withdraw(v) self.balance=self.balance-v end a:withdraw(100.0) --冒号的效果相当于在函数定义和函数调用的时候,增加一个额外的隐藏参数 --我们可以使用dot语法定义函数而用冒号语法调用函数,反之亦然,只要我们正确的处理好额外的参数. --dot语法定义时要加上self参数,调用时要传入相应的对象,冒号语法不用self参数,调用时也不需要相应的参数对象
Lua中对象没有类,每个对象有一个原型prototype,当调用不属于对象的某些操作时,会最先会到prototype中查找这些操作。
Account={balance=0} function Account:withdraw(v) self.balance=self.balance-v end function Account:deposit(v) self.balance=self.balance+v end function Account:new(o) o=o or {} setmetatable(o,self)--Account成为o的原型 self.__index=self return o end a=Account:new{balance=0} print(a.balance)--输出0 a:deposit(100.00) print(a.balance)--输出100
Account={balance=0} function Account:withdraw(v) if v>self.balance then error"insufficient funds" end self.balance=self.balance-v end function Account:deposit(v) self.balance=self.balance+v end function Account:new(o) o=o or {} setmetatable(o,self)--Account成为o的原型 self.__index=self return o end SpecialAccount=Account:new() function SpecialAccount:getLimit() return self.limit or 0 end --子类可以重定义从父类中继承来的方法 function SpecialAccount:withdraw(v) if v-self.balance>=self:getLimit() then error"insufficeint funds" end self.balance=self.balance-v end s=SpecialAccount:new{limit=1000.00} function s:getLimit() return self.balance*0.1 end s:withdraw(200.0)--该调用将运行SpecialAccount的withdraw方法,但是当 --方法调用self:getLimit时,最后的定义被触发.
原文:http://www.cnblogs.com/ljygoodgoodstudydaydayup/p/4459735.html