automaticly remove unused detached npc inventories that havn't been changed or loaded for more than 600 seconds

This commit is contained in:
Sokomine 2024-02-15 21:18:10 +01:00
parent cc15431cb2
commit 6f51ddd10d

View File

@ -3,6 +3,9 @@
-- cache the inventory of NPCs for easier access
yl_speak_up.npc_inventory = {}
-- used so that unused inventories are not immediately discarded:
yl_speak_up.npc_inventory_last_used = {}
-- where are they stored on the disk?
yl_speak_up.get_inventory_save_path = function(n_id)
return yl_speak_up.worldpath .. yl_speak_up.inventory_path .. DIR_DELIM .. "inv_" .. n_id .. ".json"
@ -35,6 +38,8 @@ yl_speak_up.save_npc_inventory = function( n_id )
if(not(n_id) or not(yl_speak_up.npc_inventory[ n_id ])) then
return
end
-- the inv was just saved - make sure it is kept in memory a bit
yl_speak_up.npc_inventory_last_used[ n_id ] = os.time()
-- convert the inventory data to something we can actually store
local inv = yl_speak_up.npc_inventory[ n_id ]
local inv_as_table = {}
@ -100,6 +105,25 @@ yl_speak_up.load_npc_inventory = function(n_id)
if(not(n_id)) then
return
end
-- clean up no longer needed detached inventories
local recently_used = os.time() - 600 -- used in the last 10 minutes
for id, data in pairs(yl_speak_up.npc_inventory) do
-- not the one for this particular NPC,
if(id and id ~= n_id and data
-- and has not been used recently:
and yl_speak_up.npc_inventory_last_used[id]
and yl_speak_up.npc_inventory_last_used[id] < recently_used
-- and not if anyone is talking to it
and not(yl_speak_up.npc_is_in_conversation(id))) then
-- actually remove that detached inventory:
minetest.remove_detached_inventory("yl_speak_up_npc_"..tostring(id))
-- delete it here as well:
yl_speak_up.npc_inventory[id] = nil
end
end
yl_speak_up.npc_inventory_last_used[ n_id ] = os.time()
-- the inventory is already loaded
if( yl_speak_up.npc_inventory[ n_id ]) then
return