Posted 08 April 2012 - 08:29 PM
DESCRIPTION
This API allows the user to set variables that can be used between applications, and will remain persistent as long as the computer exists
HOW TO USE
Save the code below as persistentVar in the apis folder of your computer, or if you want to share the api between your computers, save it in mods/ComputerCraft//lua/rom/apis
example use:
* The above code, stores "whatever" in a file /vars/SomeVariable.var (in the data aree of the computer)
* To delete a variable, simply set the variable to nil
SOURCE CODE
This API allows the user to set variables that can be used between applications, and will remain persistent as long as the computer exists
HOW TO USE
Save the code below as persistentVar in the apis folder of your computer, or if you want to share the api between your computers, save it in mods/ComputerCraft//lua/rom/apis
example use:
os.loadAPI("apis/persistentVar") -- Only use this line if you copied the API in your computers apis folder
local state=persistentVar:new("/vars")
state.SomeVariable="whatever"
print(state.SomeVariable)
* The above code, stores "whatever" in a file /vars/SomeVariable.var (in the data aree of the computer)
* To delete a variable, simply set the variable to nil
SOURCE CODE
-- ================================================
-- Persistent variables
-- ================================================
local function getVariableFilename(tbl,name)
assert(name:sub(1,1)~="_","Variable names cannot start with _")
assert(not name:find("[:/*|<>;%s]"),"Variable name contains illegal variable, you cannot use ://*|<>;%s")
local filePath=rawget(tbl,"_PVarPath")
local fileName = fs.combine(filePath,name..".var")
if not fs.exists(filePath) then
fs.makeDir(filePath)
end
return fileName
end
function new(tbl,pathName)
local v={_PVarPath=pathName or "/vars/"}
setmetatable(v,
{ __index=function(tbl,name)
local vFile=getVariableFilename(tbl,name)
local f = io.open(vFile, "r")
if f then
local content = textutils.unserialize(f:read())
f:close()
return content
else
return nil
end
end,
__newindex=function(tbl,name,value)
local vFile=getVariableFilename(tbl,name)
if value then
local f = io.open(vFile, "w")
assert(f,"FAIL: could not open file")
f:write(textutils.serialize(value))
f:close()
else
fs.delete(vFile)
end
end
})
return v
end