Lua编程中如何实现队列?
在Lua中可以采用不同的方法来声明队列;最基本的一种是利用tables和repeat函数,取两个变量来帮助我们从队列中插入和删除元素。
示例
考虑下面显示的代码-
queue = {}
queue.first = 0
queue.last = -1
queue.data = {}
function insert(q, val)
q.last =q.last+ 1
q.data[q.last] = val
end
function remove(q)
if (q.first > q.last) then
rval = -1
else
print("remove: q.data[q.first]= ", q.data[q.first], " q.first= ", q.first)
local rval = q.data[q.first]
print("remove: rval= ", rval)
q.data[q.first] = nil
q.first=q.first+ 1
print("remove: q.first= ", q.first)
end
return rval
end
insert(queue,"a")
insert(queue,"b")
insert(queue,"c")
for i,v in ipairs(queue.data) do
print(i, v)
end
repeat
local x = remove(queue)
print("list item= ", x)
until (queue.first > queue.last)输出结果1 b 2 c remove: q.data[q.first]= a q.first= 0 remove: rval= a remove: q.first= 1 list item= nil remove: q.data[q.first]= b q.first= 1 remove: rval= b remove: q.first= 2 list item= nil remove: q.data[q.first]= c q.first= 2 remove: rval= c remove: q.first= 3 list item= nil
热门推荐
10 朋友新年祝福语大全 简短
11 新年祝福语简短大方兔年
12 搬新家礼物祝福语简短
13 同学见面花束祝福语简短
14 五一假期祝福语幽默简短
15 离职欢送敬酒祝福语简短
16 对学弟的祝福语简短
17 考老师辞职祝福语简短
18 祝福语驱散霉运的话简短