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;
16 local log = function (type, msg) return log(type, "datamanager", msg); end
19 local urlcodes = setmetatable({}, { __index = function (t, k) t[k] = char(tonumber("0x"..k)); return t[k]; end });
22 return s and (s:gsub("+", " "):gsub("%%([a-fA-F0-9][a-fA-F0-9])", urlcodes));
26 return s and (s:gsub("%W", function (c) return format("%%%x", c:byte()); end));
30 local function basicSerialize (o)
31 if type(o) == "number" or type(o) == "boolean" then
33 else -- assume it is a string
34 return format("%q", tostring(o))
39 local function simplesave (f, o)
40 if type(o) == "number" then
42 elseif type(o) == "string" then
43 f:write(format("%q", o))
44 elseif type(o) == "table" then
46 for k,v in pairs(o) do
47 f:write(" [", basicSerialize(k), "] = ")
53 error("cannot serialize a " .. type(o))
57 ------- API -------------
59 function getpath(username, host, datastore)
61 return format("data/%s/%s/%s.dat", encode(host), datastore, encode(username));
63 return format("data/%s/%s.dat", encode(host), datastore);
65 return format("data/%s.dat", datastore);
69 function load(username, host, datastore)
70 local data, ret = loadfile(getpath(username, host, datastore));
71 if not data then log("warn", "Failed to load "..datastore.." storage ('"..ret.."') for user: "..username.."@"..host); return nil; end
73 local success, ret = pcall(data);
74 if not success then log("error", "Unable to load "..datastore.." storage ('"..ret.."') for user: "..username.."@"..host); return nil; end
78 function store(username, host, datastore, data)
79 local f, msg = io_open(getpath(username, host, datastore), "w+");
80 if not f then log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..username.."@"..host); return nil; end