-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathqueue.lua
111 lines (89 loc) · 2.23 KB
/
queue.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by Dee.
--- DateTime: 2019/3/7 11:27
--- FIFO
---
queue = queue or {}
---@return Queue
function queue.create()
---数据容器
local data = {}
---数据长度
local lenght = 0
---队首索引
local first = 1
---获取队首值
local peek = function()
return data[first]
end
---压入数据
local enqueue = function(v)
assert(v ~= nil, "nil value")
first = lenght == 0 and 1 or first
lenght = lenght + 1
table.insert(data, first+lenght-1, v)
end
---弹出数据
local dequeue = function()
assert(lenght > 0, "nill queue")
local ret = peek()
data[first] = nil
first = first+1
lenght = lenght - 1
first = lenght == 0 and 1 or first
if math.fmod(first, 4) == 0 then
local tmp = {}
table.move(data, first, first + lenght, 1, tmp)
first = 1
data = nil
data = tmp
end
return ret
end
local clear = function()
data = {}
first = 1
lenght = 0
end
local __tostring = function()
local tmp = {}
for i=1,lenght do
tmp[i] = data[i + first - 1]
end
return table.concat(tmp, ",")
end
local __len = function()
return lenght
end
local __index = function(i_t, key)
error(">> Dee: Limited access")
end
local __newindex = function(i_t, key, v)
error(">> Dee: Limited access")
end
local __ipairs = function(i_t)
local idx = 0
local function iter(i_t)
idx = idx + 1
if idx <= lenght then
return idx, data[first + idx - 1]
end
end
return iter
end
local __pairs = function(i_t)
error(">> Dee: Limited access")
end
local mt = {__tostring = __tostring, __index = __index, __newindex = __newindex, __ipairs = __ipairs, __pairs = __pairs, __len = __len}
---@class Queue
local t = {
enqueue = enqueue,
dequeue = dequeue,
peek = peek,
clear = clear
}
setmetatable(t, mt)
return t
end
return queue