properly handling errors in module loaders in package library (avoid lingering entry in "loading" table); throwing an error in robot library if its not a robot; automatically trying to load modules in interpreter (somewhat experimental)

This commit is contained in:
Florian Nücke 2014-01-29 20:37:41 +01:00
parent 6df7c8aed1
commit 3c1eaf165b
3 changed files with 18 additions and 8 deletions

View File

@ -3,9 +3,16 @@ local package = require("package")
local term = require("term")
local text = require("text")
local function optrequire(...)
local success, module = pcall(require, ...)
if success then
return module
end
end
local history = {}
local env = setmetatable({}, {__index = function(t, k)
return _ENV[k] or package.loaded[k]
return _ENV[k] or optrequire(k)
end})
component.gpu.setForeground(0xFFFFFF)

View File

@ -74,12 +74,12 @@ table.insert(package.searchers, pathSearcher)
function require(module)
checkArg(1, module, "string")
if loaded[module] then
if loaded[module] ~= nil then
return loaded[module]
elseif not loading[module] then
loading[module] = true
local loader, value, errorMsg = nil, nil, {"module '" .. module .. "' not found:"}
for i=1, #package.searchers do
for i = 1, #package.searchers do
local f, extra = package.searchers[i](module)
if f and type(f) ~= "string" then
loader = f
@ -90,20 +90,23 @@ function require(module)
end
end
if loader then
local result = loader(module, value)
local success, result = pcall(loader, module, value)
loading[module] = false
if not success then
error(result, 2)
end
if result then
loaded[module] = result
elseif not loaded[module] then
loaded[module] = true
end
loading[module] = false
return loaded[module]
else
loading[module] = false
error(table.concat(errorMsg, "\n"))
error(table.concat(errorMsg, "\n"), 2)
end
else
error("already loading: " .. module)
error("already loading: " .. module, 2)
end
end

View File

@ -3,7 +3,7 @@ local computer = require("computer")
local sides = require("sides")
if not computer.isRobot() then
return nil, "not a robot"
error("not a robot")
end
local robot = {}