fix(auto_require): 改进模块加载的错误处理和全局环境管理

修改自动加载模块的错误处理逻辑,增加对加载失败情况的打印输出
重构全局环境管理,使用原始require函数并优化metatable处理
This commit is contained in:
2025-09-01 18:10:19 +08:00
parent eec11a2845
commit 98a2116c19
2 changed files with 32 additions and 12 deletions

View File

@@ -1,6 +1,7 @@
-- auto_require.lua: Automatically require libraries when accessed -- auto_require.lua: Automatically require libraries when accessed
local original_ENV = _ENV -- Save the original require function
local original_require = require
-- List of common libraries to auto-require -- List of common libraries to auto-require
local common_libs = { local common_libs = {
@@ -12,7 +13,7 @@ local common_libs = {
-- Pre-load common libraries into a cache -- Pre-load common libraries into a cache
local lib_cache = {} local lib_cache = {}
for _, lib_name in ipairs(common_libs) do for _, lib_name in ipairs(common_libs) do
local success, lib = pcall(require, lib_name) local success, lib = pcall(original_require, lib_name)
if success then if success then
lib_cache[lib_name] = lib lib_cache[lib_name] = lib
end end
@@ -20,9 +21,9 @@ end
-- Create a new environment with auto-require functionality -- Create a new environment with auto-require functionality
local auto_env = setmetatable({}, { local auto_env = setmetatable({}, {
__index = function(_, key) __index = function(_, key)
-- Check if the key exists in the original environment -- Check if the key exists in the global environment
local val = original_ENV[key] local val = rawget(_G, key)
if val ~= nil then if val ~= nil then
return val return val
end end
@@ -32,8 +33,8 @@ local auto_env = setmetatable({}, {
return lib_cache[key] return lib_cache[key]
end end
-- Try to require the module -- Try to require the module using the original require function
local success, lib = pcall(require, key) local success, lib = pcall(original_require, key)
if success then if success then
lib_cache[key] = lib lib_cache[key] = lib
return lib return lib
@@ -44,9 +45,25 @@ local auto_env = setmetatable({}, {
end end
}) })
-- Replace the global environment with our auto-require environment -- Create a proxy function for require that uses the original require
setmetatable(_G, { _G.require = function(modname)
__index = auto_env return original_require(modname)
}) end
-- Add the auto-require environment to the global metatable
local old_mt = getmetatable(_G) or {}
local old_index = old_mt.__index
old_mt.__index = function(t, key)
-- Try the original index first
if old_index then
local val = old_index(t, key)
if val ~= nil then
return val
end
end
-- Then try our auto-require environment
return auto_env[key]
end
setmetatable(_G, old_mt)
return {} return {}

View File

@@ -1,2 +1,5 @@
-- Load auto_require module to automatically require libraries -- Load auto_require module to automatically require libraries
require("auto_require") local success, err = pcall(require, "auto_require")
if not success then
print("Failed to load auto_require module: " .. tostring(err))
end