You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

46 lines
2.4 KiB

  1. --- TSerial v1.3, a simple table serializer which turns tables into Lua script
  2. -- @author Taehl (SelfMadeSpirit@gmail.com)
  3. TSerial = {}
  4. --- Serializes a table into a string, in form of Lua script.
  5. -- @param t table to be serialized (may not contain any circular reference)
  6. -- @param drop if true, unserializable types will be silently dropped instead of raising errors
  7. -- if drop is a function, it will be called to serialize unsupported types
  8. -- @param indent if true, output "human readable" mode with newlines and indentation (for debug)
  9. -- @return string recreating given table
  10. function TSerial.pack(t, drop, indent)
  11. assert(type(t) == "table", "Can only TSerial.pack tables.")
  12. local s, indent = "{"..(indent and "\n" or ""), indent and math.max(type(indent)=="number" and indent or 0,0)
  13. for k, v in pairs(t) do
  14. local tk, tv, skip = type(k), type(v)
  15. if tk == "boolean" then k = k and "[true]" or "[false]"
  16. elseif tk == "string" then if string.format("%q",k) ~= '"'..k..'"' then k = '['..string.format("%q",k)..']' end
  17. elseif tk == "number" then k = "["..k.."]"
  18. elseif tk == "table" then k = "["..TSerial.pack(k, drop, indent and indent+1).."]"
  19. elseif type(drop) == "function" then k = "["..string.format("%q",drop(k)).."]"
  20. elseif drop then skip = true
  21. else error("Attempted to TSerial.pack a table with an invalid key: "..tostring(k))
  22. end
  23. if tv == "boolean" then v = v and "true" or "false"
  24. elseif tv == "string" then v = string.format("%q", v)
  25. elseif tv == "number" then -- no change needed
  26. elseif tv == "table" then v = TSerial.pack(v, drop, indent and indent+1)
  27. elseif type(drop) == "function" then v = "["..string.format("%q",drop(v)).."]"
  28. elseif drop then skip = true
  29. else error("Attempted to TSerial.pack a table with an invalid value: "..tostring(v))
  30. end
  31. if not skip then s = s..string.rep("\t",indent or 0)..k.."="..v..","..(indent and "\n" or "") end
  32. end
  33. return s..string.rep("\t",(indent or 1)-1).."}"
  34. end
  35. --- Loads a table into memory from a string (like those output by Tserial.pack)
  36. -- @param s a string of Lua defining a table, such as "{2,4,8,ex="ample"}"
  37. -- @return a table recreated from the given string
  38. function TSerial.unpack(s)
  39. assert(type(s) == "string", "Can only TSerial.unpack strings.")
  40. assert(loadstring("TSerial.table="..s))()
  41. local t = TSerial.table
  42. TSerial.table = nil
  43. return t
  44. end