Skip to content

Instantly share code, notes, and snippets.

@blasti
Last active March 12, 2022 17:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blasti/942a1252d8a18262c0e4809b38952522 to your computer and use it in GitHub Desktop.
Save blasti/942a1252d8a18262c0e4809b38952522 to your computer and use it in GitHub Desktop.
Simple ring buffer
ringbuf={}
ringbuf.eof=0
ringbuf.size=0
ringbuf.__index=ringbuf
function ringbuf:new(size)
size=tonumber(size)
if not size then
return nil, "arg must be an number"
elseif size<1 then
return nil, "out of range"
end
return setmetatable({size=size},self)
end
function ringbuf:add(value)
self.eof=self.eof<self.size and self.eof+1 or 1
self[self.eof]=tostring(value)
end
function ringbuf:get(index)
index=tonumber(index)
if not index then
return nil, "arg must be an number"
elseif index<1 or index>self.size then
return nil, "out of range"
end
if not self[self.size] then
return self[index]
end
index=self.eof+index
index=index>self.size and index-self.size or index
return self[index]
end
function ringbuf:concat()
local buf={}
local len=0
for value in self:iterator() do
len=len+1
buf[len]=value
end
return table.concat(buf)
end
function ringbuf:iterator()
local i=0
return function()
if i<=self.size then
i=i+1
return self:get(i)
end
end
end
t=ringbuf:new(5)
t:add(1)
t:add(2)
print(t:concat())
t:add(3)
t:add(4)
print(t:get(1), t:get(2))
print(t:concat())
for value in t:iterator() do
print(value)
end
t:add(5)
print(t:get(1), t:get(2))
print(t:concat())
t:add(6)
print(t:get(1), t:get(2), t:get(5))
print(t:concat())
t:add(7)
t:add(8)
print(t:get(1), t:get(2), t:get(5))
print(t:concat())
t:add(9)
t:add(10)
t:add(11)
print(t:get(1), t:get(2), t:get(5))
print(t:concat())
for value in t:iterator() do
print(value)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment