Fixed the ejabberd importer to work with the pipe sign "|" as a separator in erlang...
[prosody.git] / tools / serialize.lua
1 \r
2 local indent = function(i)\r
3         return string.rep("\t", i);\r
4 end\r
5 local function basicSerialize (o)\r
6         if type(o) == "number" or type(o) == "boolean" then\r
7                 return tostring(o);\r
8         else -- assume it is a string -- FIXME make sure it's a string. throw an error otherwise.\r
9                 return (string.format("%q", tostring(o)):gsub("\\\n", "\\n"));\r
10         end\r
11 end\r
12 local function _simplesave (o, ind, t)\r
13         if type(o) == "number" then\r
14                 table.insert(t, tostring(o));\r
15         elseif type(o) == "string" then\r
16                 table.insert(t, (string.format("%q", o):gsub("\\\n", "\\n")));\r
17         elseif type(o) == "table" then\r
18                 table.insert(t, "{\n");\r
19                 for k,v in pairs(o) do\r
20                         table.insert(t, indent(ind));\r
21                         table.insert(t, "[");\r
22                         table.insert(t, basicSerialize(k));\r
23                         table.insert(t, "] = ");\r
24                         _simplesave(v, ind+1, t);\r
25                         table.insert(t, ",\n");\r
26                 end\r
27                 table.insert(t, indent(ind-1));\r
28                 table.insert(t, "}");\r
29         elseif type(o) == "boolean" then\r
30                 table.insert(t, (o and "true" or "false"));\r
31         else\r
32                 error("cannot serialize a " .. type(o))\r
33         end\r
34 end\r
35 local t_concat = table.concat;\r
36 \r
37 module "serialize"\r
38 \r
39 function serialize(o)\r
40         local t = {};\r
41         _simplesave(o, 1, t);\r
42         return t_concat(t);\r
43 end\r
44 \r
45 return _M;\r