fix new battery plugin to work better with multiple batteries present
[wmiirc-lua.git] / src / core / history.lua
blobe6cc666f35458d47973fef46e35eb6317d5dfb57
2 local os = require("os")
3 local io = require("io")
4 local string = require("string")
5 -- local posix = require("posix")
6 -- local table = require("table")
7 -- local math = require("math")
8 -- local type = type
9 -- local error = error
10 local print = print
11 -- local pcall = pcall
12 -- local pairs = pairs
13 -- local package = package
14 -- local require = require
15 local tostring = tostring
16 -- local tonumber = tonumber
17 local setmetatable = setmetatable
19 module("history")
22 history = {}
23 function new (size)
24 local o = {}
26 setmetatable (o,history)
27 history.__index = history
29 o.data = {}
30 o.data[size] = nil
31 o.size = size
32 o.count = 0
33 o.last = 0
35 return o
36 end
38 function history:add (entry)
39 if self.count < self.size then
40 self.count = self.count + 1
41 self.last = self.count
42 self.data[self.last] = entry
43 else
44 self.last = 1 + (self.last % self.size)
45 self.data[self.last] = entry
46 end
47 end
49 function history:oldest ()
50 if self.count then
51 local i = 1 + ((self.last + self.size - self.count) % self.size)
52 return self.data[i]
53 end
54 return nil
55 end
57 function history:newest ()
58 if self.count then
59 return self.data[self.last]
60 end
61 return nil
62 end
64 function history:walk_reverse ()
65 local s = self
66 local count = s.count
67 local index = s.last
69 return function ()
70 local ret = nil
71 if count > 0 then
72 local i = 1 + (s.size + index - 1) % s.size
73 ret = s.data[i]
74 count = count - 1
75 index = index - 1
76 end
77 return ret
78 end
79 end
81 function history:walk_reverse_unique ()
82 local s = self
84 local iterator = s:walk_reverse()
85 if not iterator then
86 return function ()
87 return nil
88 end
89 end
91 local seen = {}
92 return function ()
93 local v = iterator()
94 while v do
95 if not seen[v] then
96 seen[v] = 1
97 return v
98 end
99 v = iterator()