从代码上说明
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)