Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function serialize(dat,options)
- options=options or {}
- local out=""
- local queue={{dat}}
- local cv=0
- local keydat
- local ptbl={}
- while queue[1] do
- local cu=queue[1]
- table.remove(queue,1)
- local typ=type(cu[1])
- local ot
- if typ=="string" then
- ot=string.gsub(string.format("%q",cu[1]),"\\\n","\\n")
- elseif typ=="number" or typ=="boolean" or typ=="nil" then
- ot=tostring(cu[1])
- elseif typ=="table" then
- local empty=true
- ot="{"
- local st=0
- ptbl[#ptbl+1]=cu[1]
- for k,v in pairs(cu[1]) do
- empty=false
- st=st+1
- table.insert(queue,st,{k,"key"})
- st=st+1
- local val=v
- if type(v)=="table" then
- for n,l in pairs(ptbl) do
- if l==v then
- if options.nofalse then
- val="recursive"
- elseif options.noerror then
- return false
- else
- error("Cannot handle recursive tables.",2)
- end
- end
- end
- end
- table.insert(queue,st,{val,"value",nil,st/2})
- end
- if empty then
- ot=ot.."}"
- ptbl[#ptbl]=nil
- typ="emptytable"
- else
- cv=cv+1
- if cu[3] then
- queue[st][3]=cu[3]
- cu[3]=nil
- end
- queue[st][3]=(queue[st][3] or 0)+1
- end
- elseif typ=="function" then
- if options.nofunc then
- ot="function"
- else
- local e,r,er=pcall(string.dump,cu[1])
- if e and r then
- ot="f(\""..r:gsub(".",function(c)
- return "\\"..tostring(string.byte(c)) end
- ).."\")"
- else
- if options.nofalse then
- ot="invalid function"
- elseif options.noerror then
- return false
- else
- error(r or er,2)
- end
- end
- end
- end
- if cu[2]=="key" then
- if type(ot)=="string" then
- local nt=ot:sub(2,-2)
- local e,r=loadstring("return {"..nt.."=true}")
- if options.noshortkey or not e then
- ot="["..ot.."]="
- else
- ot=nt.."="
- end
- else
- ot=ot.."="
- end
- keydat={cu[1],ot}
- ot=""
- elseif cu[2]=="value" then
- if keydat[1]~=cu[4] then
- ot=keydat[2]..ot
- end
- if cu[3] then
- ot=ot..("}"):rep(cu[3])
- for l1=1,cu[3] do
- ptbl[#ptbl]=nil
- end
- cv=cv-cu[3]
- if cv~=0 then
- ot=ot..","
- end
- elseif typ~="table" then
- ot=ot..","
- end
- end
- out=out..ot
- end
- return out
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement