lua-users home
lua-l archive

Re: require() relative to calling file

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


On 7 February 2017 at 02:23, Stephen Irons <stephen.irons@clear.net.nz> wrote:
> However, in the source code, it is package.searchpath() (file
> loadlib.c, function searchpath()) that implements the way Lua finds
> modules. searchpath() modifies the name of the module to find
> (replacing '.' with the directory separator), then takes a list of
> path templates (from package.path), replaces '?' with the modified
> name of the module, and passes each in turn to the C standard function
> fopen(). This code is all very straightforward, with no special cases.
>
What I would like is that package.searchpath() would replace another
character, like '$' with the directory where the function calling
'request' resides. a crude implementation:
--------------
local function getcallingdir(lvl)
 for i = (lvl or 2), 1000 do
 local fi = debug.getinfo(i, 'S')
 if not fi then break end
 if fi.source and fi.source:sub(1,1) == '@' then
 local fname = fi.short_src or fi.source:sub(2)
 return fname:match('^(.*)/[^/]*$') or fname
 end
 end
end
local oldsearch=package.searchpath
function package.searchpath (name, path, sep, rep)
 local calldir = getcallingdir(3)
 if calldir then
 path = path:gsub('%$', calldir)
 end
 return oldsearch(name, path, sep, rep)
end
-----------------------
something like this would make it easy to write multi-source-file
packages that can be installed anywhere, or even used as a "private"
part of a bigger bundle. a "main" file could require() other
submodules with relative paths from itself, instead of having to
specify the whole path or making all pieces directly visible to all
scripts.
-- 
Javier

AltStyle によって変換されたページ (->オリジナル) /