Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

maybe fix recursive module loads? #468

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
42 changes: 33 additions & 9 deletions lib/luvit/module.lua
Expand Up @@ -39,6 +39,8 @@ local function partialRealpath(filepath)
return path.normalize(filepath)
end

package.loading = {}

local function myloadfile(filepath)
if not fs.existsSync(filepath) then return end

Expand All @@ -57,16 +59,38 @@ local function myloadfile(filepath)
assert(fn, err)
local dirname = path.dirname(filepath)
local realRequire = require
setfenv(fn, setmetatable({
__filename = filepath,
__dirname = dirname,
require = function (filepath)
return realRequire(filepath, dirname)
end,
}, global_meta))
local module = fn()
local exports = {}
exports.__filename = filepath
exports.__dirname = dirname
exports.exports = package.loading[filepath] or {}
exports.require = function(filepath)
local function exists(fn)
if pcall(function () fs.statSync(fn) end) then
return fn
end
end

local stem = path.normalize(path.join(dirname, filepath))
local realName = exists(stem) or exists(stem .. '.lua') or exists(stem .. '.luvit') or exists(stem .. 'init.lua') or exists(stem .. 'init.luvit')

if not realName then
return realRequire(filepath)
end

if package.loading[realName] then
return package.loading[realName]
end

local m = realRequire(filepath, dirname) or package.loading[realName]
package.loading[realName] = nil
return m
end
local fn = setfenv(fn, setmetatable(exports, global_meta))
package.loading[filepath] = exports.exports
local module = fn() or package.loading[filepath]
package.loaded[filepath] = module
return function() return module end
package.loading[filepath] = nil
return function() return package.loaded[filepath] end
end
module.myloadfile = myloadfile

Expand Down