Skip to content

Instantly share code, notes, and snippets.

@upvalue
Created January 11, 2013 01:45
Show Gist options
  • Save upvalue/4507290 to your computer and use it in GitHub Desktop.
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.
-- 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