lua-users home
lua-l archive

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

On 4 February 2017 at 20:23, Sean Conner <> wrote:
>   Where do you add the "application path"?  Do you prepend it to
> package.path?  Or append it to package.path?

You don't want to modify package.path for this type of functionality.
A key note is that the string you pass to the `require` function is
what the module is saved under in `package.loaded`.
It *has* to be something a function that wraps or re-implements
`require` itself.

Now I ask: why are we taking about this in relation to file systems?
package searchers can be abstract, and don't have to be bound by a
file system layout.
I think the only reasonable way to accomplish a 'relative require' is
to use the *current* module path as a prefix.
Assuming the current file was loaded with require, this can be done as
Soni notes: `require((...)..".mysubmodule")`
To make things neater, this can be made into a function with use of
the debug library:

function rr(str)
    local info
    local lvl = 3
    while true do
        info = debug.getinfo(lvl, "f")
        if info == nil or info.func == require then
        lvl = lvl + 1
    if info then
        local _, require_prefix = debug.getlocal(lvl-1, -1)
        return require(require_prefix.."."..str)
        return require(str)

Though I perhaps prefer the explicit-ness of
`require((...)..".mysubmodule")` itself.


Back when I was first starting with lua, I did find myself wanting
relative require.
However as time has gone on I wanted it less and less, and now don't
have any desire for it at all.

I think the main desire for a relative require was a reluctance to
name my projects while I was working on them.
If I had a sub-module 'foo' that relied on a sub-module "bar", I'd
have to name the whole project!