lua setmetatable

-- create class

Account = {balance = 0}

-- construct

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"insuficient funds"
     end
     self.balance = self.balance -v 
end

-- use example
a = Account:new()
print(a.balance)      --> 0
a:deposit(1000.00)
a:withdraw(100.00)
print(a.balance)      --> 900

  

posted @ 2017-07-18 15:27  hao.ma  阅读(1638)  评论(0编辑  收藏  举报