Guest User

Untitled

a guest
Dec 8th, 2012
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.19 KB | None | 0 0
  1. function serializeImpl(t) -- converts anything into a string
  2. local sType = type(t)
  3. if sType == "table" then
  4. local lstcnt=0
  5. for k,v in pairs(t) do
  6. lstcnt = lstcnt + 1
  7. end
  8. local result = "{"
  9. local aset=1
  10. local comma=false
  11. for k,v in pairs(t) do
  12. comma=true
  13. if k==aset then
  14. result = result..serializeImpl(v)..","
  15. aset=aset+1
  16. else
  17. result = result..("["..serializeImpl(k).."]="..serializeImpl(v)..",")
  18. end
  19. end
  20. if comma then
  21. result=string.sub(result,1,-2)
  22. end
  23. result = result.."}"
  24. return result
  25. elseif sType == "string" then
  26. return string.format("%q",t) -- improved from textutils
  27. elseif sType == "number" or sType == "boolean" or sType == "nil" then
  28. return tostring(t)
  29. elseif sType == "function" and not TF then -- function i added
  30. local status,data=pcall(string.dump,t) -- convert the function into a string
  31. if status then
  32. return 'func('..string.format("%q",data)..')' -- format it so it dosent screw up syntax
  33. else
  34. error()
  35. end
  36. elseif sType == "function" and TF then
  37. return tostring(t)
  38. else
  39. error()
  40. end
  41. end
  42.  
  43. function split(T,func) -- splits a table
  44. if func then
  45. T=func(T) -- advanced function
  46. end
  47. local Out={}
  48. if type(T)=="table" then
  49. for k,v in pairs(T) do
  50. Out[split(k)]=split(v) -- set the values for the new table
  51. end
  52. else
  53. Out=T
  54. end
  55. return Out
  56. end
  57.  
  58. function serialize( t ) -- TODO: combine with serializeImpl
  59. t=split(t)
  60. return serializeImpl( t, tTracking )
  61. end
  62.  
  63. function unserialize(s,tf) -- converts a string back into its original form
  64. if type(s)~="string" then
  65. error("String exepcted. got "..type(s),2)
  66. end
  67. local func, e = loadstring( "return "..s, "serialize" )
  68. local funcs={} -- a table to store all the functions generated by f() (for securety)
  69. if not func then
  70. error("Invalid string.")
  71. end
  72. setfenv( func, { -- make sure nothing can be called within the function
  73. func=function(S) -- puts function requests into the funcs table
  74. local new={}
  75. funcs[new]=S
  76. return new
  77. end,
  78. })
  79. return split(func(),function(val) -- apply functions if any
  80. if funcs[val] then
  81. return loadstring(funcs[val])
  82. else
  83. return val
  84. end
  85. end)
  86. end
Advertisement
Add Comment
Please, Sign In to add comment