forked from Hyperion/HyperionOS
rewrite
This commit is contained in:
56
Test/Hyperion-kernel-v0.1.0/lib/modules/Hyperion/11_require.kmod
Executable file
56
Test/Hyperion-kernel-v0.1.0/lib/modules/Hyperion/11_require.kmod
Executable file
@@ -0,0 +1,56 @@
|
||||
local args = {...}
|
||||
local kernel = args[1]
|
||||
|
||||
-- List of search paths
|
||||
local paths = {
|
||||
"/lib/?",
|
||||
"/usr/lib/?",
|
||||
"/usr/local/lib/?"
|
||||
}
|
||||
|
||||
-- Custom require implementation
|
||||
function require(module)
|
||||
-- Return cached module if it already exists
|
||||
if kernel.cache.preload[module] then
|
||||
return kernel.cache.preload[module]
|
||||
end
|
||||
|
||||
local err = {}
|
||||
|
||||
for _, path in ipairs(paths) do
|
||||
-- Replace "?" with module name
|
||||
local filePath = string.replace(path, "?", module)
|
||||
|
||||
-- Try to open file
|
||||
local file = kernel.fs.isFile(filePath)
|
||||
if file then
|
||||
local content = kernel.fs.readAllText(filePath)
|
||||
|
||||
-- Load the module as Lua code
|
||||
local chunk, loadErr = load(content, filePath)
|
||||
if not chunk then
|
||||
table.insert(err, "Error loading: " .. filePath .. ": " .. loadErr)
|
||||
else
|
||||
-- Execute the module. If the module returns a value, cache it.
|
||||
local ok, result = xpcall(chunk, debug.traceback)
|
||||
if not ok then
|
||||
table.insert(err, "Error executing: "..filePath..": "..tostring(result))
|
||||
else
|
||||
if result ~= nil then
|
||||
kernel.cache.preload[module] = result
|
||||
return result
|
||||
end
|
||||
|
||||
-- If module doesn't return anything, cache `true` like Lua does
|
||||
kernel.cache.preload[module] = true
|
||||
return true
|
||||
end
|
||||
end
|
||||
else
|
||||
table.insert(err, "Module not found: " .. filePath)
|
||||
end
|
||||
end
|
||||
|
||||
-- If nothing worked, raise an error with all reasons
|
||||
error("Unable to require module '" .. module .. "':\n" .. table.concat(err, "\n"))
|
||||
end
|
||||
Reference in New Issue
Block a user