Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- infutil={}
- local function serializeImpl(t,TF)
- local sType = type(t)
- if sType == "table" then
- local result = "{"
- local aset=1
- local comma=false
- for k,v in pairs(t) do
- comma=true
- if k==aset then
- result = result..serializeImpl(v,TF)..","
- aset=aset+1
- else
- local tmp=serializeImpl(k,TF)
- local tmp2=serializeImpl(v,TF)
- if type(k)=="string" then
- if pcall(loadstring,"return {"..k.."="..tmp2.."}") and not string.find(k,",") then
- result=result..k.."="..tmp2..","
- else
- result=result.."["..tmp.."]="..tmp2..","
- end
- else
- result=result.."["..tmp.."]="..tmp2..","
- end
- end
- end
- if comma then
- result=string.sub(result,1,-2)
- end
- result = result.."}"
- return result
- elseif sType == "string" then
- return string.gsub(string.format("%q",t),"\\\n","\\n")
- elseif sType == "number" or sType == "boolean" or sType == "nil" then
- return tostring(t)
- elseif sType == "function" and not TF then
- local status,data=pcall(string.dump,t)
- if status then
- return 'func('..string.format("%q",data)..')'
- else
- error()
- end
- elseif sType == "function" and TF then
- return tostring(t)
- else
- error()
- end
- end
- function infutil.split(T,func)
- if func then
- T=func(T)
- end
- local Out={}
- if type(T)=="table" then
- for k,v in pairs(T) do
- Out[infutil.split(k)]=infutil.split(v)
- end
- else
- Out=T
- end
- return Out
- end
- function infutil.serialize(t,TF)
- t=infutil.split(t)
- return serializeImpl(t,TF)
- end
- function infutil.unserialize(s,tf)
- if type(s)~="string" then
- error("String exepcted. got "..type(s),2)
- end
- local func,e=loadstring("return"..s,"unserialize")
- local funcs={}
- if not func then
- error("Invalid string.")
- end
- setfenv(func,{
- func=function(S)
- local new={}
- funcs[new]=S
- return new
- end,
- })
- return infutil.split(func(),function(val)
- if funcs[val] then
- return loadstring(funcs[val])
- else
- return val
- end
- end)
- end
- function infutil.savePrefs(name,data)
- local S=infutil.serialize(data)
- if not S then
- return false
- end
- love.filesystem.write(name,S)
- end
- function infutil.readPrefs(name)
- if not love.filesystem.exists(name) then
- return false
- end
- return infutil.unserialize(love.filesystem.read(name))
- end
- function infutil.compress(...)
- local E,D=pcall(infutil.serialize,{...})
- if E then
- return string.sub(D,2,-2)
- else
- return false
- end
- end
- function infutil.decompress(S)
- if not S then
- return false
- end
- local E,D,C=pcall(infutil.unserialize,"{"..S.."}")
- if C or not E then
- return false
- else
- return type(D)=="table" and D
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement