# HG changeset patch # User Matthew Wild # Date 1433343067 -3600 # Node ID d4a6c9ee4bc5f5a2036be1e95a0173a36be850d3 # Parent 7889515bac86a6853c3034d4777a6b4e4ce9212e util.queue: Allow optional wrap-around when pushing, overwriting oldest unread item diff -r 7889515bac86 -r d4a6c9ee4bc5 util/queue.lua --- a/util/queue.lua Sat May 30 22:23:19 2015 +0100 +++ b/util/queue.lua Wed Jun 03 15:51:07 2015 +0100 @@ -11,7 +11,7 @@ local have_utable, utable = pcall(require, "util.table"); -- For pre-allocation of table -local function new(size) +local function new(size, allow_wrapping) -- Head is next insert, tail is next read local head, tail = 1, 1; local items = 0; -- Number of stored items @@ -22,7 +22,12 @@ count = function (self) return items; end; push = function (self, item) if items >= size then - return nil, "queue full"; + if allow_wrapping then + tail = (tail%size)+1; -- Advance to next oldest item + items = items - 1; + else + return nil, "queue full"; + end end t[head] = item; items = items + 1;