magicalities/storage.lua

68 lines
1.6 KiB
Lua
Raw Normal View History

2019-08-11 18:38:24 +00:00
--[[
JSON storage information:
"<player name>": {
"recipes": [<list of item names that this player knows how to craft>],
"abilities": [<list of learned abilities that are not crafting recipes>],
"protect": [<list of player protected nodes (positions)>],
"research": <integer of research points>,
}
]]
2019-08-28 14:15:55 +00:00
-- Modstorage
local storage = minetest.get_mod_storage()
2019-08-11 18:38:24 +00:00
-- Memory cache
magicalities.data = {}
-- Storage actions
2019-08-11 18:38:24 +00:00
function magicalities.load_player_data(player_name)
2019-08-28 14:15:55 +00:00
local stdata = minetest.deserialize(storage:get_string(player_name))
if not stdata then
2019-08-11 18:38:24 +00:00
magicalities.data[player_name] = {
recipes = {},
abilities = {},
protect = {},
research = 0,
}
return
end
2019-08-28 14:15:55 +00:00
magicalities.data[player_name] = stdata
2019-08-11 18:38:24 +00:00
end
function magicalities.save_player_data(player_name)
2019-08-28 14:15:55 +00:00
if not magicalities.data[player_name] then return end
local data = magicalities.data[player_name]
2019-08-11 18:38:24 +00:00
2019-08-28 14:15:55 +00:00
-- Do not save empty data
if #data.recipes == 0 and #data.abilities == 0 and #data.protect == 0 and data.research == 0 then return end
2019-08-11 18:38:24 +00:00
2019-08-28 14:15:55 +00:00
local str = minetest.serialize(data)
2019-08-11 18:38:24 +00:00
2019-08-28 14:15:55 +00:00
storage:set_string(player_name, str)
2019-08-11 18:38:24 +00:00
end
function magicalities.save_all_data()
for pname in pairs(magicalities.data) do
minetest.after(0.1, magicalities.save_player_data, pname)
end
end
-- System Actions
2019-08-11 18:38:24 +00:00
minetest.register_on_shutdown(magicalities.save_all_data)
minetest.register_on_joinplayer(function (player)
magicalities.load_player_data(player:get_player_name())
end)
minetest.register_on_leaveplayer(function (player, timed)
local name = player:get_player_name()
magicalities.save_player_data(name)
if timed then return end
magicalities.data[name] = nil
end)