lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


I've adapted the simplifed `require()` found in PiL 2nd ed. to
hopefully match the C implementation (beside the stack trace that
starts one level deeper).

It works around an "yield across C boundary" issue when using the
MoonScript loader with OpenResty. The first resumes a coroutine at
parse time, and the latter runs request handlers in coroutines.
Requiring a MoonScript file from a handler breaks because of this,
since `require()` is a C function.

I plan to release it as a Rock and want to make sure it is correct.

For Lua 5.1:

    -- package and package.loaded are cached, while package.loaders isn't.
    local package, p_loaded = package, package.loaded

    function require (name)
        if not p_loaded[name] then
            local msg = {}
            local loader
            for _, searcher in ipairs(package.loaders) do
                loader = searcher(name)
                if type(loader) == "function" then break end
                if type(loader) == "string" then
                    -- `loader` is actually an error message
                    msg[#msg + 1] = loader
                end
            end
            if loader == nil then
                error("module '" .. name .. "' not
found:"..table.concat(msg), 2)
            end
            p_loaded[name] = true
            local res = loader(name)
            if res ~= nil then
                p_loaded[name] = res
            end
        end
        return p_loaded[name]
    end

While I'm at it, is it correct for Lua 5.2?

-            local loader
+            local loader, param
-              loader = searcher(name)
+              loader, param = searcher(name)
-          local res = loader(name)
+          local res = loader(name, param)

Thanks in advance :-)

—Pierre-Yves