Comparison

util/datamanager.lua @ 1381:46a58df8557d

util.datamanager: Allow multiple data storage callbacks, and allow them to modify parameters
author Matthew Wild <mwild1@gmail.com>
date Mon, 22 Jun 2009 14:15:33 +0100
parent 1097:c5b33640a5f0
child 1462:44780b856ce7
comparison
equal deleted inserted replaced
1380:9b3b43b8963a 1381:46a58df8557d
48 end 48 end
49 return path; 49 return path;
50 end 50 end
51 51
52 local data_path = "data"; 52 local data_path = "data";
53 local callback; 53 local callbacks = {};
54 54
55 ------- API ------------- 55 ------- API -------------
56 56
57 function set_data_path(path) 57 function set_data_path(path)
58 log("debug", "Setting data path to: %s", path); 58 log("debug", "Setting data path to: %s", path);
59 data_path = path; 59 data_path = path;
60 end 60 end
61 function set_callback(func) 61
62 callback = func; 62 local function callback(username, host, datastore, data)
63 for _, f in ipairs(callbacks) do
64 username, host, datastore, data = f(username, host, datastore, data);
65 if not username then break; end
66 end
67
68 return username, host, datastore, data;
69 end
70 function add_callback(func)
71 if not callbacks[func] then -- Would you really want to set the same callback more than once?
72 callbacks[func] = true;
73 callbacks[#callbacks+1] = func;
74 return true;
75 end
76 end
77 function remove_callback(func)
78 if callbacks[func] then
79 for i, f in ipairs(callbacks) do
80 if f == func then
81 callbacks[i] = nil;
82 callbacks[f] = nil;
83 return true;
84 end
85 end
86 end
63 end 87 end
64 88
65 function getpath(username, host, datastore, ext, create) 89 function getpath(username, host, datastore, ext, create)
66 ext = ext or "dat"; 90 ext = ext or "dat";
67 host = host and encode(host); 91 host = host and encode(host);
95 119
96 function store(username, host, datastore, data) 120 function store(username, host, datastore, data)
97 if not data then 121 if not data then
98 data = {}; 122 data = {};
99 end 123 end
100 if callback and callback(username, host, datastore) then return true; end 124
125 username, host, datastore, data = callback(username, host, datastore, data);
126 if not username then
127 return true; -- Don't save this data at all
128 end
129
101 -- save the datastore 130 -- save the datastore
102 local f, msg = io_open(getpath(username, host, datastore, nil, true), "w+"); 131 local f, msg = io_open(getpath(username, host, datastore, nil, true), "w+");
103 if not f then 132 if not f then
104 log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..(username or "nil").."@"..(host or "nil")); 133 log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..(username or "nil").."@"..(host or "nil"));
105 return; 134 return;