-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRingBuffer.lua
More file actions
60 lines (48 loc) · 1.18 KB
/
RingBuffer.lua
File metadata and controls
60 lines (48 loc) · 1.18 KB
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
-- Import
local Class = require "Class"
local error = error
local RingBuffer = Class{
head = 0,
bufferSize = 0,
buffer = {}
}
setfenv(1, RingBuffer)
function RingBuffer:init(size)
self.bufferSize = size
end
function RingBuffer:size()
return self.bufferSize
end
function RingBuffer:elementCount()
return #self.buffer
end
function RingBuffer:isFull()
return self.bufferSize == #self.buffer
end
function RingBuffer:getElement(index)
if index > self:elementCount() or index <= 0 then
error("Index out of bounds")
end
local absoluteIndex = ((self.head - 1) + (index - 1) - (self:elementCount() - 1)) % self.bufferSize + 1
return self.buffer[absoluteIndex]
end
function RingBuffer:insertElement(e)
self.head = (self.head % self.bufferSize) + 1
self.buffer[self.head] = e
end
function RingBuffer:headElement()
return self.buffer[self.head]
end
function reverseIterator(cB, range)
local i = cB:elementCount()
if range == nil then
range = i
end
return function()
if i >= cB:elementCount() - range then
i = i - 1
return i + 1, cB:getElement(i + 1)
end
end
end
return RingBuffer