This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
oreillynz's profile picture

[1.3+] O'Reillys Persistent Variables (Tables, Encryption, Namespaces...)

Started by oreillynz, 05 April 2012 - 12:17 PM
oreillynz #1
Posted 05 April 2012 - 02:17 PM
Why another persistent variable api?

- Accepts table's within tables, and self referencing tables thanks to immibis' awesome serialize library
- For the paranoid, you can 'drop in' encryption and decryption functions
- Very simple to use


Requirements

- Immibis' serialize
- Tomass' String Utils


About Namespaces

Namespaces are for things like different programs, eg "Router", so you don't need to worry about multiple programs messing up each other's saved position or similar behaviour. If a namespace contains the '/' character, it will be treated like a file path, and sub directories will be created within that namespace.


Functions
Spoilerpersistent.update( "Namespace", "variable name", value )
Will change a variable to the value given, and create a new file for it if required.
Value can be a string, number, boolean, table…


persistent.read("Namespace", "variable name")
Will return the value of the variable, already cast into it's correct type.


persistent.exists("Namespace", "variable name")
Returns "true" if the variable exists, "false" otherwise


persistent.delete("Namespace", "variable name")
Removes the variable if it exists, by deleting the file.


Usage
Spoiler

--assuming the API is saved under a folder called "oreilly"
os.loadAPI("/oreilly/persistent")

-- you don't need to 'create' variables in advance - it's all automatic
persistent.update("Namespace","Variable","Value")
persistent.read("Namespace","Variable")

-- complex tables 'just work' thanks to Immibis
example={a=10,b=20,c="Hello world!",d={another="table"}}
example.e=example
persistent.update("testing","table",example)
result.e.a
-- prints 10
result.e.a + result.b
-- prints 30
result.d.another
-- prints "table"

-- last, easy existence checking and removal
persistent.exists("testing","table")
-- prints "true"
persistent.delete("testing","table")
-- will remove the file, and therefore the variable


Using encryption:
SpoilerThere are two function variables that you set to matching encryption and decryption functions - persistent_encryption and persistent_decryption.
The encryption function will be passed a binary string (the output from Immibis' serialize) and will need to return a string that will be written to the variable's file. As expected, the decryption function will need to mirror this.


What can persistent variables be used for?

Saving and then building a blueprints via nestled tables
Remembering a computers location + messages for GPS and router systems
Letting computers remember what program they were running and what they were doing when they start,
Or having turtles remember where they are…


Code:

Spoiler

--Copyright (C) Paul O'Reilly, paul.oreilly@digime.co.nz
--[[
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
The software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. in no event shall the author be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software or the use or other dealings in the software.
]]

os.loadAPI("/strutils/StrUtils")
os.loadAPI("/immibis/serialize")

persistent_path = "/var"
if fs.exists( persistent_path ) == false then fs.makeDir( persistent_path ) end

function _doNothing( value ) return value end
persistent_encryption = _doNothing
persistent_decryption = _doNothing


function _getpersistentVariablePath( path, name )
	-- will create path if required
	local complete_path = persistent_path..'/'..path
	local path_fragments = StrUtils.seperate(complete_path, "/")
	local current_path = ""
	for k,v in pairs( path_fragments ) do
		current_path = current_path.."/"..v
		if not fs.exists( current_path ) then fs.makeDir( current_path ) end
	end  
	return complete_path.."/"..name..".var"
end


function exists( path, name )
	local path = _getpersistentVariablePath( path, name )
	return fs.exists( path )
end


function delete( path, name )
	local variable_path = _getpersistentVariablePath( path, name )
	if exists( path, name ) then fs.delete( variable_path )
	else return "Variable doesn't exist"
	end
end


function update( path, name, value )
	local variable_path = _getpersistentVariablePath( path, name )
	local as_string = serialize.serialize( value )
	if not ( persistent_encryption == nil ) then
		as_string = persistent_encryption( as_string )
	end
	local persistent_file = io.open( variable_path, "w" )
	if persistent_file then
		persistent_file:write( as_string )
		persistent_file:close()
	else return "Error opening file" end
end


function read( path, name )
	local variable_path = _getpersistentVariablePath( path, name )
	if fs.exists( variable_path ) then
		local persistent_file = io.open( variable_path, "r" )
		if persistent_file then
			content = persistent_file:read("*a")
			persistent_file:close()
			if not ( persistent_decryption == nil ) then
				content = persistent_decryption( content )
			end
			return serialize.deserialize( content )
		else return "Error opening file" end
	else return "Variable doesn't exist"
	end
end



The API assumes StrUtils is find in "/strutils/StrUtils" and serialize in "/immibis/serialize" - this can easily be changed at the top of the code.
Ciber #2
Posted 08 April 2012 - 07:24 AM
Nice, very usefull