[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: require() relative to calling file
- From: Russell Haley <russ.haley@...>
- Date: Tue, 7 Feb 2017 22:46:56 -0500
On Tue, Feb 7, 2017 at 5:59 AM, Javier Guerra Giraldez
<javier@guerrag.com> wrote:
> 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
>
Thank you, Javier! I'm travelling on business so I won't get to this
until next week but will definitely try it out asap.
Russ
- References:
- require() relative to calling file, tobias
- Re: require() relative to calling file, Sean Conner
- Re: require() relative to calling file, Russell Haley
- Re: require() relative to calling file, Scott Morgan
- Re: require() relative to calling file, Russell Haley
- Re: require() relative to calling file, Sean Conner
- Re: require() relative to calling file, Russell Haley
- Re: require() relative to calling file, Sean Conner
- Re: require() relative to calling file, Russell Haley
- Re: require() relative to calling file, Stephen Irons
- Re: require() relative to calling file, Javier Guerra Giraldez