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;
15 local log = function (type, msg) return log(type, "datamanager", msg); end
18 local urlcodes = setmetatable({}, { __index = function (t, k) t[k] = char(tonumber("0x"..k)); return t[k]; end });
21 return s and (s:gsub("+", " "):gsub("%%([a-fA-F0-9][a-fA-F0-9])", urlcodes));
25 return s and (s:gsub("%W", function (c) return format("%%%x", c:byte()); end));
29 local function basicSerialize (o)
30 if type(o) == "number" or type(o) == "boolean" then
32 else -- assume it is a string
33 return string.format("%q", tostring(o))
38 local function simplesave (f, o)
39 if type(o) == "number" then
41 elseif type(o) == "string" then
42 f:write(format("%q", o))
43 elseif type(o) == "table" then
45 for k,v in pairs(o) do
46 f:write(" [", format("%q", k), "] = ")
52 error("cannot serialize a " .. type(o))
56 ------- API -------------
58 function getpath(username, host, datastore)
59 return format("data/%s/%s/%s.dat", encode(host), datastore, encode(username));
62 function load(username, host, datastore)
63 local data, ret = loadfile(getpath(username, host, datastore));
64 if not data then log("warn", "Failed to load "..datastore.." storage ('"..ret.."') for user: "..username.."@"..host); return nil; end
66 local success, ret = pcall(data);
67 if not success then log("error", "Unable to load "..datastore.." storage ('"..ret.."') for user: "..username.."@"..host); return nil; end
71 function store(username, host, datastore, data)
72 local f, msg = io_open(getpath(username, host, datastore), "w+");
73 if not f then log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..username.."@"..host); return nil; end