Skip to content

Instantly share code, notes, and snippets.

@q962
Last active August 1, 2024 09:07
Show Gist options
  • Save q962/d7c87753240de7105520800acd7bab93 to your computer and use it in GitHub Desktop.
Save q962/d7c87753240de7105520800acd7bab93 to your computer and use it in GitHub Desktop.
Lua require relative path fix
local realRequire = require;
local function get_source_dir()
local up = debug.getinfo(3).source:gsub("\\", "/");
if up:sub(1, 1) ~= '@' then
return realRequire(name);
end
up = up:sub(2)
local sep_index = find_sep(up);
if sep_index ~= 0 then
return up:sub(1, sep_index)
end
return
end
local function find_sep(s)
local sep_index = 0;
local _s = 1
while _s do
_s = s:find("/", _s)
if _s then
sep_index = _s;
_s = _s + 1
else
break
end
end
return sep_index
end
local function relative_require(name)
-- fix relative path
if name:sub(1, 1) == '.' then
local _name = name:gsub("\\", "/");
local rela_path = _name:match("^[./]+")
local short_name = _name:sub(#rela_path + 1)
local source_dir = get_source_dir()
local old_ppath = package.path;
if source_dir then
local pdir = (source_dir .. "/" .. rela_path .. "/"):gsub("//", "/")
package.path = pdir .. "?.lua;" .. pdir .. "?/init.lua;" .. package.path
end
local ret = realRequire(short_name)
package.path = old_ppath;
return ret;
else
return realRequire(name)
end
end
function require(name)
if not name or #name == 0 then
return realRequire(name)
end
return relative_require(name)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment