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