lua 面向对象编程

案例1:

Account={balance=0}

function Account.withdraw(self,v)
	self.balance = self.balance - v
end

function Account.print(self)
	print("Account.balance:" .. tostring(self.balance))
end
a1 = Account
a1.withdraw(a1,100.0)
a1.print(a1)

案例2:

function Account:withdraw(v)
	self.balance = self.balance - v
end

function Account:print()
	print("Account.balance:" .. tostring(self.balance))
end
a1 = Account
a1:withdraw(100.0)
a1:print()


案例3:

function Account:new(o)
	o = o or {}
	setmetatable(o,self)
	self.__index = self
	return o
end

a1=Account:new({balance = 0})
a1:withdraw(100)
a1:print()

a2=Account:new({balance = 0})
a2:withdraw(50)
a2:print()


继承的简单案例:

 

Account={balance=1000}

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 "insufficient funds"
	end

	self.balance = self.balance - v
end


function Account:print()
	print("balance:" .. tostring(self.balance))
end
-------------------------
-----------------------------------------------------------------------------------------------------------------

--从基类派生一个子类SpecialAccount
SpecialAccount = Account:new()

s=SpecialAccount:new({limit=1000.0})


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


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

	self.balance = self.balance - v
end

s:withdraw(100)
s:print()
s:deposit(100)
s:print()





 

 

 类的私密性简单案例:


function newAccount(initialBalance,limitParam)
	local self={
		balance = initialBalance,
		limit = limitParam,
	}


	local withdraw = function(v)
						if v - self.balance >= self.limit then
							error "insufficient funds"
						end
						self.balance = self.balance - v
					end


	local getBalance = function()
						print("balance:" .. self.balance)
					end

	return {
		withdraw = withdraw,
		getBalance = getBalance
	}
end


obj=newAccount(100,1000)
obj.withdraw(10)
obj.getBalance()



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值