lua 类继承和实现

http://blog.csdn.net/ssihc0/article/details/7742323

Account={balance=0}; --新建了一个对像,他有一个属性balance

function Account:new(o) --这里的 :new(o) 中的冒号,代码可以省略self ,在访问的时候object:new(o)  如果是点号 :new(o) 就应改成 .new(self,o)  在访问的时候 object.(object,o) 
    o= o or {}
    setmetatable(o,self); --O 继承 self   
    self.__index=self;--关联元表条目
    return o;
end

function Account.deposit(self,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

SpecialAccount=Account:new(); --create a new object class,basic Account class

s=SpecialAccount:new{limit=1000.00};--实例化一个新的SpecialAccount 对象
print (s.balance);
s:deposit(100.00);


function SpecialAccount:withdraw(v)
    if v-self.balance >= self:getLimit() then
        error "insufficient funds";
    end
    self.balance=self.balance-v;
end

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

print (s.limit);
print (s.getLimit(s))
print (s.balance)

 

posted on 2016-02-04 11:16  602147629  阅读(445)  评论(0编辑  收藏  举报