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;
17 local log = function (type, msg) return log(type, "datamanager", msg); end
20 local urlcodes = setmetatable({}, { __index = function (t, k) t[k] = char(tonumber("0x"..k)); return t[k]; end });
23 return s and (s:gsub("+", " "):gsub("%%([a-fA-F0-9][a-fA-F0-9])", urlcodes));
27 return s and (s:gsub("%W", function (c) return format("%%%x", c:byte()); end));
31 local function basicSerialize (o)
32 if type(o) == "number" or type(o) == "boolean" then
34 else -- assume it is a string
35 return format("%q", tostring(o))
40 local function simplesave (f, o)
41 if type(o) == "number" then
43 elseif type(o) == "string" then
44 f:write(format("%q", o))
45 elseif type(o) == "table" then
47 for k,v in pairs(o) do
48 f:write(" [", basicSerialize(k), "] = ")
53 elseif type(o) == "boolean" then
54 f:write(o and "true" or "false");
56 error("cannot serialize a " .. type(o))
60 ------- API -------------
62 function getpath(username, host, datastore)
64 return format("data/%s/%s/%s.dat", encode(host), datastore, encode(username));
66 return format("data/%s/%s.dat", encode(host), datastore);
68 return format("data/%s.dat", datastore);
72 function load(username, host, datastore)
73 local data, ret = loadfile(getpath(username, host, datastore));
75 log("warn", "Failed to load "..datastore.." storage ('"..ret.."') for user: "..(username or nil).."@"..(host or nil));
79 local success, ret = pcall(data);
81 log("error", "Unable to load "..datastore.." storage ('"..ret.."') for user: "..(username or nil).."@"..(host or nil));
87 function store(username, host, datastore, data)
88 local f, msg = io_open(getpath(username, host, datastore), "w+");
90 log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..(username or nil).."@"..(host or nil));