Created
January 11, 2013 01:45
-
-
Save upvalue/4507290 to your computer and use it in GitHub Desktop.
Simple circular buffers for Lua, which took me forever to get right for some reason.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Circular buffer functionality | |
local Buffer = {} | |
function Buffer:new(ob) | |
local o = ob or {} | |
o.entries = #o | |
o.cursor = #o + 1 | |
o.max = 10 | |
setmetatable(o, self) | |
self.__index = self | |
return o | |
end | |
function Buffer:append(entry) | |
if self[self.cursor] then | |
self[self.cursor] = entry | |
else | |
table.insert(self, entry) | |
end | |
self.cursor = self.cursor + 1 | |
if self.cursor == self.max + 1 then | |
self.cursor = 1 | |
end | |
if self.entries ~= self.max then | |
self.entries = self.entries + 1 | |
end | |
end | |
function Buffer:get(idx) | |
-- Allow negative indexes | |
if idx < 0 then | |
idx = (self.entries + idx) + 1 | |
end | |
if self.entries == self.max then | |
local c = self.cursor + idx - 1 | |
if c > self.max then | |
c = c - self.max | |
end | |
return self[c] | |
else | |
return self[idx] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment