案例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()