-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue.lua
More file actions
45 lines (34 loc) · 683 Bytes
/
queue.lua
File metadata and controls
45 lines (34 loc) · 683 Bytes
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
local Queue = {}
function Queue:new()
local obj = {first = 0, last = -1}
setmetatable(obj, self)
self.__index = self
return obj
end
function Queue:push(value)
local last = self.last + 1
self.last = last
self[last] = value
end
function Queue:pop()
local first = self.first
if first > self.last then error("queue is empty") end
local value = self[first]
self[first] = nil -- to allow garbage collection
self.first = first + 1
return value
end
function Queue:is_empty()
return self.first > self.last
end
-- Example usage
--[[
local q = Queue:new()
q:push(1)
q:push(2)
q:push(3)
while not q:is_empty() do
print(q:pop())
end
]]
return Queue