lua 类继承和实现


从代码上说明


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)


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值