ctf_stats: Separate save-checking code from the actual saving code

This allows mods to directly call ctf_stats.save without having to pass unnecessary params like force_save = true.
This commit is contained in:
ANAND 2020-05-14 23:54:28 +05:30
parent baf5f17878
commit f1a2006ec5

View file

@ -57,6 +57,8 @@ function ctf_stats.load_legacy()
return true return true
end end
-- Load persistant data from mod storage (or legacy file)
-- and initialize empty tables where required
function ctf_stats.load() function ctf_stats.load()
if not ctf_stats.load_legacy() then if not ctf_stats.load_legacy() then
for _, key in pairs(data_to_persist) do for _, key in pairs(data_to_persist) do
@ -90,20 +92,26 @@ function ctf_stats.load()
end end
end end
function ctf_stats.save(force_save) -- Save persistant data to mod storage
if not _needs_save and not force_save then function ctf_stats.save()
return
end
_needs_save = false
for _, key in pairs(data_to_persist) do for _, key in pairs(data_to_persist) do
storage:set_string(key, minetest.write_json(ctf_stats[key])) storage:set_string(key, minetest.write_json(ctf_stats[key]))
end end
end
-- Separate recursion to check if save required and then call ctf_stats.save
-- This allows ctf_stats.save to be called directly when an immediate save is required
local function check_if_save_needed()
if _needs_save then
ctf_stats.save()
_needs_save = false
end
minetest.after(13, check_if_save_needed)
end
minetest.after(13, check_if_save_needed)
minetest.after(13, ctf_stats.save) minetest.after(13, ctf_stats.save)
end end
minetest.after(13, ctf_stats.save)
function ctf_stats.player_or_nil(name) function ctf_stats.player_or_nil(name)
return ctf_stats.players[name], ctf_stats.current.red[name] or ctf_stats.current.blue[name] return ctf_stats.players[name], ctf_stats.current.red[name] or ctf_stats.current.blue[name]
@ -248,7 +256,8 @@ ctf_match.register_on_winner(function(winner)
ctf_stats.prev_match_summary = fs ctf_stats.prev_match_summary = fs
storage:set_string("prev_match_summary", fs) storage:set_string("prev_match_summary", fs)
ctf_stats.save(true) -- Flush data to mod_storage at the end of each match
ctf_stats.save()
end) end)
ctf_match.register_on_skip_match(function() ctf_match.register_on_skip_match(function()
@ -266,7 +275,7 @@ ctf_match.register_on_skip_match(function()
ctf_stats.prev_match_summary = fs ctf_stats.prev_match_summary = fs
storage:set_string("prev_match_summary", fs) storage:set_string("prev_match_summary", fs)
ctf_stats.save(true) ctf_stats.save()
end) end)
ctf_match.register_on_new_match(function() ctf_match.register_on_new_match(function()