Skip to content

Instantly share code, notes, and snippets.

@DelusionalLogic
Created December 27, 2012 12:28
StateManager lib
local OBJDEF = { varsion = 1.0 }
local JSON = (loadfile "JSON")()
local function exploreTable(table, resultTable)
local varCount = 0
if resultTable == nil then
resultTable = {}
end
for k,v in pairs(table) do
if(type(v) == "table") then
resultTable[k] = exploreTable(v, resultTable[k])
varCount = varCount + 1
end
if type(v) == "number" or type(v) == "string" then
resultTable[k] = v
varCount = varCount + 1
end
end
if varCount ~= 0 then
return resultTable
else
return
end
end
function OBJDEF:saveState(stateName, globalTable)
fs.makeDir("states")
local file = fs.open("states/"..stateName, "w")
file.write(JSON:encode(exploreTable(globalTable)))
file.flush()
file.close()
end
local function restoreTable(table, saveTable)
for k,v in pairs(saveTable) do
if type(v) == "table" then
if table[k] == nil then
table[k] = v
else
restoreTable(table[k], saveTable[k])
end
end
if type(v) == "number" or type(v) == "string" then
table[k] = v
end
end
end
function OBJDEF:loadState(stateName, globalTable)
local file = fs.open("states/"..stateName, "r")
local state = file.readAll()
file.close()
restoreTable(globalTable, JSON:decode(state))
end
function OBJDEF.__tostring()
return "StateManager"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment