opus/sys/modules/opus/history.lua

51 lines
944 B
Lua
Raw Permalink Normal View History

local Util = require('opus.util')
2016-12-11 19:24:52 +00:00
2017-10-03 04:50:54 +00:00
local History = { }
local History_mt = { __index = History }
2016-12-11 19:24:52 +00:00
function History.load(filename, limit)
2018-01-24 22:39:38 +00:00
local self = setmetatable({
limit = limit,
filename = filename,
}, History_mt)
2016-12-11 19:24:52 +00:00
2018-01-24 22:39:38 +00:00
self.entries = Util.readLines(filename) or { }
self.pos = #self.entries + 1
2016-12-11 19:24:52 +00:00
2018-01-24 22:39:38 +00:00
return self
2017-10-03 04:50:54 +00:00
end
2016-12-11 19:24:52 +00:00
2017-10-03 04:50:54 +00:00
function History:add(line)
2018-01-24 22:39:38 +00:00
if line ~= self.entries[#self.entries] then
table.insert(self.entries, line)
if self.limit then
while #self.entries > self.limit do
table.remove(self.entries, 1)
end
end
Util.writeLines(self.filename, self.entries)
self.pos = #self.entries + 1
end
2017-10-03 04:50:54 +00:00
end
function History:reset()
2018-01-24 22:39:38 +00:00
self.pos = #self.entries + 1
2017-10-03 04:50:54 +00:00
end
function History:back()
2018-01-24 22:39:38 +00:00
if self.pos > 1 then
self.pos = self.pos - 1
return self.entries[self.pos]
end
2017-10-03 04:50:54 +00:00
end
function History:forward()
2018-01-24 22:39:38 +00:00
if self.pos <= #self.entries then
self.pos = self.pos + 1
return self.entries[self.pos]
end
2016-12-11 19:24:52 +00:00
end
return History