ComputerCraft Archive

history

computer utility kepler155c github

Description

ComputerCraft OS

Installation

Copy one of these commands into your ComputerCraft terminal:

wget:wget https://raw.githubusercontent.com/kepler155c/opus/develop-1.8/sys/modules/opus/history.lua history
Archive:wget https://cc.shobie.xyz/cc/get/gh-kepler155c-opus-sys-modules-opus-history history
Quick Install: wget https://cc.shobie.xyz/cc/get/gh-kepler155c-opus-sys-modules-opus-history history

Usage

Run: history

Tags

none

Source

View Original Source

Code Preview

local Util = require('opus.util')

local History    = { }
local History_mt = { __index = History }

function History.load(filename, limit)

	local self = setmetatable({
		limit = limit,
		filename = filename,
	}, History_mt)

	self.entries = Util.readLines(filename) or { }
	self.pos = #self.entries + 1

	return self
end

function History:add(line)
	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
end

function History:reset()
	self.pos = #self.entries + 1
end

function History:back()
	if self.pos > 1 then
		self.pos = self.pos - 1
		return self.entries[self.pos]
	end
end

function History:forward()
	if self.pos <= #self.entries then
		self.pos = self.pos + 1
		return self.entries[self.pos]
	end
end

return History