]> git.lizzy.rs Git - elidragon_v2.git/blob - mods/elidragon_db/init.lua
Fix DB system crashes and implement custom directory support
[elidragon_v2.git] / mods / elidragon_db / init.lua
1 local class = elidragon.class
2
3 local db = {}
4
5 local private = {}
6 local worldpath = minetest.get_worldpath()
7
8 function db:constructor(name, initial_data, dir, env)
9         private[self] = {env = env or _G, path = (dir or worldpath) .. "/" .. name .. ".json"}
10         self:load(initial_data or {})
11 end
12
13 function db:load(initial_data)
14         local _self = private[self]
15         local file = _self.env.io.open(_self.path, "r")
16         local data = file and minetest.parse_json(file:read()) or {}
17         if file then
18                 file:close()
19         end
20         for k, v in pairs(data) do
21                 self[k] = v
22         end
23         for k, v in pairs(initial_data) do
24                 if not rawget(self, k) then
25                         self[k] = v
26                 end
27         end
28 end
29
30 function db:save()
31         local _self = private[self]
32         local file = assert(_self.env.io.open(_self.path, "w"))
33         file:write(minetest.write_json(self))
34         file:close()
35 end
36
37 function db:close()
38         self:save()
39         private[self] = nil
40 end
41
42 minetest.register_on_shutdown(function()
43         for d in pairs(private) do
44                 d:save()
45         end
46 end)
47
48 elidragon.db = class(db)