-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathQueue_pico8.lua
68 lines (50 loc) · 1.12 KB
/
Queue_pico8.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
--[[
--------------------------------
Queue implementation for Lua (PICO-8 Version)
Inspired by Queue.js (http://code.iamkate.com/javascript/queues/)
Github: https://github.com/darkwark/queue-lua
March, 2020
--------------------------------
]]--
queue = {}
function queue:new()
local object = {}
object.list = {}
object.offset = 1
self.__index = self
return setmetatable(object, self)
end
function queue:length()
return #self.list - self.offset
end
function queue:isempty()
return #self.list == 0
end
function queue:enqueue(item)
add(self.list, item)
return self
end
function queue:peek()
if not self:isempty() then
return self.list[self.offset]
end
return nil
end
function queue:dequeue()
if self:isempty() then return nil end
local item = self.list[self.offset]
self.offset = self.offset + 1
if (self.offset * 2) >= #self.list then
self:optimize()
end
return item
end
function queue:optimize()
local pos, new = 1, {}
for i = self.offset, #self.list do
new[pos] = self.list[i]
pos = pos + 1
end
self.offset = 1
self.list = new
end