lua程序设计(第四版)练习答案自做(第二十一章)

文章目录

仓库

21.1

#!/usr/bin/lua
Stack={}
function Stack:isempty()
	return #self==0
end
function Stack:push(v)
	table.insert(self,v)
end
function Stack:pop()
	if #self~=0 then
		table.remove(self)
	else
		error("Stack is empty")
	end
end
function Stack:top()
	if #self~=0 then
		return self[#self]
	else
		return nil
	end
end
function Stack:new(o)
	o=o or {}
	self.__index=self
	setmetatable(o,self)
	return o
end


---------------------
s=Stack:new({2})
print("top is "..s:top())
s:push(3)
print("top is "..s:top())
s:pop()
print("top is "..s:top())
s:pop()
if s:isempty() then
	print("stack is empty!!!")
end

21.2

#!/usr/bin/lua
Stack={}
function Stack:isempty()
	return #self==0
end
function Stack:push(v)
	table.insert(self,v)
end
function Stack:pop()
	if #self~=0 then
		table.remove(self)
	else
		error("Stack is empty")
	end
end
function Stack:top()
	if #self~=0 then
		return self[#self]
	else
		return nil
	end
end
function Stack:new(o)
	o=o or {}
	self.__index=self
	setmetatable(o,self)
	return o
end
--以上是Stack类的定义
StackQueue=Stack:new()
function StackQueue:insertbottom(v)
	table.insert(self,1,v)
end


--以上是StackQueue的定义


---------------------
s=StackQueue:new({2})
print("top is "..s:top())
s:push(3)
print("top is "..s:top())
s:insertbottom(5)
s:pop()
print("top is "..s:top())
s:pop()
print("bottom is "..s:top())
s:pop()
if s:isempty() then
	print("stack is empty!!!")
end

21.3

#!/usr/bin/lua
local metadata={}
Stack={}
function Stack:isempty()
	return #metadata[self]==0
end
function Stack:push(v)
	table.insert(metadata[self],v)
end
function Stack:pop()
	if #metadata[self]~=0 then
		table.remove(metadata[self])
	else
		error("Stack is empty")
	end
end
function Stack:top()
	if #metadata[self]~=0 then
		return metadata[self][#metadata[self]]
	else
		return nil
	end
end
function Stack:new(o)
	o=o or {}
	self.__index=self
	setmetatable(o,self)
	metadata[o]={}
	return o
end


---------------------
s=Stack:new()
s:push(3)
print("top is "..s:top())
s:push(4)
print("top is "..s:top())
s:pop()
s:pop()
if s:isempty() then
	print("stack is empty!!!")
end

21.4

#!/usr/bin/lua
function newAccount(initialBalance)
	local o={balance=initialBalance or 0}
	local proxy={}
	local mt={
		balance=function ()
			return o.balance
		end,
		withdraw=function (v)
			o.balance=o.balance-v
		end,
		deposit=function (v)
			o.balance=o.balance+v
		end,
}
		mt.__index=mt
	setmetatable(proxy,mt)
	return proxy
end







a=newAccount(103)
b=newAccount()
a.deposit(100.0)
b.withdraw(20)
print(a.balance())
print(b.balance())
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值