79 lines
1.8 KiB
Lua
79 lines
1.8 KiB
Lua
|
------------------------------------------------
|
||
|
--作者: gzg
|
||
|
--日期: 2021-02-20
|
||
|
--文件: Queue.lua
|
||
|
--模块: Queue
|
||
|
--描述: 队列,执行先进先出的原则
|
||
|
------------------------------------------------
|
||
|
local Queue = {}
|
||
|
Queue.__index = Queue
|
||
|
|
||
|
--创建一个新的Queue。obj 可 nil, isNotCopy 默认深度拷贝
|
||
|
function Queue:New(obj, isNotCopy)
|
||
|
local _Queue = nil
|
||
|
if obj ~= nil then
|
||
|
if type(obj) =="table" then
|
||
|
_Queue = isNotCopy and obj or Utils.DeepCopy(obj)
|
||
|
else
|
||
|
_Queue = {first = 0, last = -1}
|
||
|
for i = 0, obj.Count - 1 do
|
||
|
table.insert(_Queue, obj[i])
|
||
|
end
|
||
|
end
|
||
|
else
|
||
|
_Queue = {first = 0, last = -1}
|
||
|
end
|
||
|
setmetatable(_Queue, Queue)
|
||
|
return _Queue
|
||
|
end
|
||
|
|
||
|
|
||
|
--往队列尾部增加一个数据
|
||
|
function Queue:Enqueue(item)
|
||
|
local _last = self.last + 1;
|
||
|
self.last = _last;
|
||
|
self[_last] = item;
|
||
|
end
|
||
|
|
||
|
--返回一个队列头部的数据,并删除之
|
||
|
function Queue:Dequeue()
|
||
|
local _first = self.first
|
||
|
if _first > self.last then
|
||
|
error("List is empty")
|
||
|
end
|
||
|
local value = self[_first]
|
||
|
self[_first] = nil
|
||
|
self.first = _first + 1
|
||
|
return value
|
||
|
end
|
||
|
|
||
|
--返回一个队列头部的数据
|
||
|
function Queue:Peek()
|
||
|
local _first = self.first
|
||
|
if _first > self.last then
|
||
|
error("List is empty")
|
||
|
end
|
||
|
return self[_first];
|
||
|
end
|
||
|
|
||
|
--清除所有队列所有内容
|
||
|
function Queue:Clear()
|
||
|
local _count = #self;
|
||
|
for i=_count, 1, -1 do
|
||
|
table.remove(self)
|
||
|
end
|
||
|
self.first = 0;
|
||
|
self.last = -1;
|
||
|
end
|
||
|
|
||
|
--item的数量
|
||
|
function Queue:Count()
|
||
|
return self.last - self.first + 1;
|
||
|
end
|
||
|
|
||
|
-- eg: UIUtils.CSFormat("{0}{1}",_Queue:Unpack())
|
||
|
function Queue:Unpack()
|
||
|
return table.unpack(self);
|
||
|
end
|
||
|
|
||
|
return Queue
|