lua 面向对象编程
发布时间:2020-12-14 22:09:35 所属栏目:大数据 来源:网络整理
导读:案例1: Account={balance=0}function Account.withdraw(self,v)self.balance = self.balance - vendfunction Account.print(self)print("Account.balance:" .. tostring(self.balance))enda1 = Accounta1.withdraw(a1,100.0)a1.print(a1) 案例2: function
案例1: Account={balance=0} function Account.withdraw(self,v) self.balance = self.balance - v end function Account.print(self) print("Account.balance:" .. tostring(self.balance)) end a1 = Account a1.withdraw(a1,100.0) a1.print(a1) 案例2:
function Account:withdraw(v) self.balance = self.balance - v end function Account:print() print("Account.balance:" .. tostring(self.balance)) end a1 = Account a1:withdraw(100.0) a1:print() 案例3:
function Account:new(o) o = o or {} setmetatable(o,self) self.__index = self return o end a1=Account:new({balance = 0}) a1:withdraw(100) a1:print() a2=Account:new({balance = 0}) a2:withdraw(50) a2:print() 继承的简单案例: ? Account={balance=1000} 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 function Account:print() print("balance:" .. tostring(self.balance)) end ------------------------- ----------------------------------------------------------------------------------------------------------------- --从基类派生一个子类SpecialAccount SpecialAccount = Account:new() s=SpecialAccount:new({limit=1000.0}) function SpecialAccount:getlimit() return self.limit or 0 end function SpecialAccount:withdraw(v) if v - self.balance >= self:getlimit() then error "insufficient funds" end self.balance = self.balance - v end s:withdraw(100) s:print() s:deposit(100) s:print()
? ?类的私密性简单案例: function newAccount(initialBalance,limitParam) local self={ balance = initialBalance,limit = limitParam,} local withdraw = function(v) if v - self.balance >= self.limit then error "insufficient funds" end self.balance = self.balance - v end local getBalance = function() print("balance:" .. self.balance) end return { withdraw = withdraw,getBalance = getBalance } end obj=newAccount(100,1000) obj.withdraw(10) obj.getBalance() (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |