From 5626163f17a252212607dc63bfcd726df44bf290 Mon Sep 17 00:00:00 2001 From: MihailRis Date: Mon, 6 Oct 2025 19:06:15 +0300 Subject: [PATCH] fix: wrong environment used in modules imported by require(...) --- res/scripts/stdmin.lua | 11 ++++++++--- src/logic/scripting/lua/lua_engine.cpp | 3 +++ src/logic/scripting/scripting.cpp | 10 ++++++++++ 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/res/scripts/stdmin.lua b/res/scripts/stdmin.lua index bbf3e7e6..f66c6644 100644 --- a/res/scripts/stdmin.lua +++ b/res/scripts/stdmin.lua @@ -558,8 +558,9 @@ local internal_locked = false -- Example `base:scripts/tests.lua` -- -- nocache - ignore cached script, load anyway -function __load_script(path, nocache) +local function __load_script(path, nocache, env) local packname, filename = parse_path(path) + print(packname, filename, env) if internal_locked and (packname == "res" or packname == "core") and filename:starts_with("modules/internal") then @@ -578,6 +579,9 @@ function __load_script(path, nocache) if script == nil then error(err) end + if env then + script = setfenv(script, env) + end local result = script() if not nocache then __cached_scripts[path] = script @@ -593,10 +597,11 @@ end function require(path) if not string.find(path, ':') then local prefix, _ = parse_path(_debug_getinfo(2).source) - return require(prefix..':'..path) + return require(prefix .. ':' .. path) end local prefix, file = parse_path(path) - return __load_script(prefix..":modules/"..file..".lua") + local env = __vc__pack_envs[prefix] + return __load_script(prefix .. ":modules/" .. file .. ".lua", nil, env) end function __scripts_cleanup() diff --git a/src/logic/scripting/lua/lua_engine.cpp b/src/logic/scripting/lua/lua_engine.cpp index 6ffa9057..875d82ea 100644 --- a/src/logic/scripting/lua/lua_engine.cpp +++ b/src/logic/scripting/lua/lua_engine.cpp @@ -104,6 +104,9 @@ void lua::init_state(State* L, StateType stateType) { pushnil(L); setglobal(L, "io"); + createtable(L, 0, 0); + setglobal(L, "__vc__pack_envs"); + const char* removed_os[] { "execute", "exit", "remove", "rename", "setlocale", "tmpname", nullptr}; remove_lib_funcs(L, "os", removed_os); diff --git a/src/logic/scripting/scripting.cpp b/src/logic/scripting/scripting.cpp index 57285945..997b5f82 100644 --- a/src/logic/scripting/scripting.cpp +++ b/src/logic/scripting/scripting.cpp @@ -181,7 +181,17 @@ std::unique_ptr scripting::start_coroutine(const io::path& script) { lua::setfield(L, "PACK_ENV"); lua::pushstring(L, pack.id); lua::setfield(L, "PACK_ID"); + + lua::dump_stack(L); + if(!lua::getglobal(L, "__vc__pack_envs")) { + lua::createtable(L, 0, 0); + lua::setglobal(L, "__vc__pack_envs"); + lua::pushvalue(L, -1); + } + lua::pushenv(L, id); + lua::setfield(L, pack.id); lua::pop(L); + return std::shared_ptr(new int(id), [=](int* id) { //-V508 lua::remove_environment(L, *id); delete id;