1 local format = string.format;
2 local setmetatable, type = setmetatable, type;
4 local char = string.char;
5 local loadfile, setfenv, pcall = loadfile, setfenv, pcall;
7 local io_open = io.open;
8 local tostring = tostring;
11 local indent = function(f, i)
23 local log = function (type, msg) return log(type, "datamanager", msg); end
26 local urlcodes = setmetatable({}, { __index = function (t, k) t[k] = char(tonumber("0x"..k)); return t[k]; end });
29 return s and (s:gsub("+", " "):gsub("%%([a-fA-F0-9][a-fA-F0-9])", urlcodes));
33 return s and (s:gsub("%W", function (c) return format("%%%x", c:byte()); end));
37 local function basicSerialize (o)
38 if type(o) == "number" or type(o) == "boolean" then
40 else -- assume it is a string -- FIXME make sure it's a string. throw an error otherwise.
41 return (format("%q", tostring(o)):gsub("\\\n", "\\n"));
46 local function simplesave (f, o, ind)
47 if type(o) == "number" then
49 elseif type(o) == "string" then
50 f:write((format("%q", o):gsub("\\\n", "\\n")))
51 elseif type(o) == "table" then
53 for k,v in pairs(o) do
55 f:write("[", basicSerialize(k), "] = ")
56 simplesave(f, v, ind+1)
61 elseif type(o) == "boolean" then
62 f:write(o and "true" or "false");
64 error("cannot serialize a " .. type(o))
68 ------- API -------------
70 function getpath(username, host, datastore)
72 return format("data/%s/%s/%s.dat", encode(host), datastore, encode(username));
74 return format("data/%s/%s.dat", encode(host), datastore);
76 return format("data/%s.dat", datastore);
80 function load(username, host, datastore)
81 local data, ret = loadfile(getpath(username, host, datastore));
83 log("warn", "Failed to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
87 local success, ret = pcall(data);
89 log("error", "Unable to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
95 function store(username, host, datastore, data)
96 local f, msg = io_open(getpath(username, host, datastore), "w+");
98 log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..(username or "nil").."@"..(host or "nil"));
102 simplesave(f, data, 1);