auto lua modules removal on quit

This commit is contained in:
MihailRis
2024-02-21 11:20:53 +03:00
parent 241570ac82
commit fcb396344c
2 changed files with 23 additions and 12 deletions
+20 -12
View File
@@ -20,8 +20,10 @@ function parse_path(path)
return string.sub(path, 1, index-1), string.sub(path, index+1, -1) return string.sub(path, 1, index-1), string.sub(path, index+1, -1)
end end
package = {
loaded={}
}
local __cached_scripts = {} local __cached_scripts = {}
local __cached_results = {}
-- Load script with caching -- Load script with caching
-- --
@@ -31,38 +33,44 @@ local __cached_results = {}
-- nocache - ignore cached script, load anyway -- nocache - ignore cached script, load anyway
function load_script(path, nocache) function load_script(path, nocache)
local packname, filename = parse_path(path) local packname, filename = parse_path(path)
local fullpath = file.resolve(path);
-- __cached_scripts used in condition because cached result may be nil -- __cached_scripts used in condition because cached result may be nil
if not nocache and __cached_scripts[fullpath] ~= nil then if not nocache and __cached_scripts[path] ~= nil then
return __cached_results[fullpath] return package.loaded[path]
end end
if not file.isfile(path) then if not file.isfile(path) then
error("script '"..filename.."' not found in '"..packname.."'") error("script '"..filename.."' not found in '"..packname.."'")
end end
local script, err = loadfile(fullpath) local script, err = loadfile(file.resolve(path))
if script == nil then if script == nil then
error(err) error(err)
end end
local result = script() local result = script()
if not nocache then if not nocache then
__cached_scripts[fullpath] = script __cached_scripts[path] = script
__cached_results[fullpath] = result package.loaded[path] = result
end end
return result return result
end end
function __scripts_cleanup()
print("cleaning scripts cache")
for k, v in pairs(__cached_scripts) do
local packname, _ = parse_path(k)
if packname ~= "core" then
print("unloaded "..k)
__cached_scripts[k] = nil
package.loaded[k] = nil
end
end
end
function require(path) function require(path)
local prefix, file = parse_path(path) local prefix, file = parse_path(path)
return load_script(prefix..":modules/"..file..".lua") return load_script(prefix..":modules/"..file..".lua")
end end
function __reset_scripts_cache()
__cached_scripts = {}
__cached_results = {}
end
function sleep(timesec) function sleep(timesec)
local start = time.uptime() local start = time.uptime()
while time.uptime() - start < timesec do while time.uptime() - start < timesec do
+3
View File
@@ -124,6 +124,9 @@ void scripting::on_world_quit() {
state->callNoThrow(0); state->callNoThrow(0);
} }
} }
if (state->getglobal("__scripts_cleanup")) {
state->callNoThrow(0);
}
scripting::level = nullptr; scripting::level = nullptr;
scripting::content = nullptr; scripting::content = nullptr;
scripting::indices = nullptr; scripting::indices = nullptr;