루 아의 대상 과 계승

3166 단어 OpenResty&nginxLua
루 아 자 체 는 대상 개념 이 없다.원 표를 이용 하여 시 뮬 레이 션 한 것.인터넷 실례 에서 직접 운행 할 수 있 는 것 은 드물다.여기에 자신 이 괴 롭 힌 코드 를 붙 여 라.실례 수정 은 《 루 아 프로 그래 밍 》 이라는 책 에서 나 왔 다.
모듈 코드 Account. lua :
Account = {balance = 0}                                                                                                                                                                                                                                                       

Account.__index = Account

function Account:new (o)
    o = o or {}   -- create object if user does not provide one
    setmetatable(o, self)
    self.__index = self
    return o
end

function Account:withdraw (v) 
    print("Call withdraw from Account obj.")
    if v > self.balance then 
        print ("insufficient funds") 
        return
    end 
    self.balance = self.balance - v 
end

function Account:deposit (v) 
    self.balance = self.balance + v 
end

function Account:getBalance()
    return self.balance;
end

SpecialAccount = {limit = 0}
SpecialAccount = Account:new()
setmetatable(SpecialAccount, Account)

SpecialAccount.__index = SpecialAccount


function SpecialAccount:new (l) 
    local self = {}
    self = Account:new()
    setmetatable(self, SpecialAccount)
        
    self.limit = l or 0
    return self
end

function SpecialAccount:withdraw (v) 
    print("Call withdraw from SpecialAccount..")
    if v - self.balance >= self:getLimit() then
        print "insufficient funds!"
        return
    end 
        self.balance = self.balance - v 
end

function SpecialAccount:getLimit()
    return self.limit or 0
end

return Account;   

호출 코드 class. lua:
--
-- class.lua                                                                                                                                                                                                                                                                  
--
local acc = require("Account")

acc_ye = Account:new()
acc_ty = Account:new()
print ("Ori : balance of ye is : "..acc_ye:getBalance()..", And balance of ty is : "..acc_ty:getBalance())
acc_ye:deposit(100)
print ("Deposit: balance of ye is : "..acc_ye:getBalance()..", And balance of ty is : "..acc_ty:getBalance())
acc_ye:withdraw(100)
acc_ty:withdraw(100)
print ("Withdraw: balance of ye is : "..acc_ye:getBalance()..", And balance of ty is : "..acc_ty:getBalance())

acc_sye = SpecialAccount:new(2000)
acc_sty = SpecialAccount:new()
print ("Ori: balance of sye is : "..acc_sye:getBalance()..", And balance of sty is : "..acc_sty:getBalance())
print ("Ori: ===Limit of sye is : "..acc_sye:getLimit()..", And limit of sty is : "..acc_sty:getLimit())
acc_sye:deposit(1000)
print ("Deposit: balance of sye is : "..acc_sye:getBalance()..", And balance of sty is : "..acc_sty:getBalance())
acc_sye:withdraw(2500)
acc_sty:withdraw(1000)
print ("Withdraw: balance of sye is : "..acc_sye:getBalance()..", And balance of sty is : "..acc_sty:getBalance())

좋은 웹페이지 즐겨찾기