lua-users home
lua-l archive

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




On 02/02/17 09:14 PM, tobias@justdreams.de wrote:

Hi,

that topic has been discussed on several places in the we (stackoverflow, etc..) and while people came up with some solutions, I haven't really seen anybody making a case against it. So I'm wondering if that behaviour could be build into Lua ...

What exactly do I mean?
-----------------------

consider the following layout:
-basedir
 \
  -scripts
   \
    -a.lua
    -b.lua

a.lua has a require('b')

Now if I do the following:
# cd basedir/scripts
# lua a.lua

everything runs smoothly.  But if I
# cd basedir
# lua scripts/a.lua

I get an error that module 'b' can't be found because the searchpath is based of the current working directory.


How to deal with it?
--------------------

Append the path of the currently executed Lua file to package.path (temporarily)
If we add the following (slighly hackish) code to loadlib.c:


// find location of current file
static void appendcurrentpath(lua_State *L, const char *pname ) {
  lua_Debug ar;
  lua_getstack( L, 2, &ar );  // needs safeguarding
  lua_getinfo( L, "S", &ar ); // needs safeguarding
  strrchr( ar.short_src, '/' )[1] = 0x00;  // cut off filename
  if (0 == strncmp(pname, "cpath", 5))
    lua_pushfstring(L, ";%s/?.so", ar.short_src );
  if (0 == strncmp(pname, "path", 4))
lua_pushfstring(L, ";%s/?.lua;%s/?/init.lua", ar.short_src, ar.short_src );
  lua_concat(L, 2);
}

and call that function from within *findfile:

static const char *findfile (lua_State *L, const char *name,
                                           const char *pname,
                                           const char *dirsep) {
  const char *path;
  lua_getfield(L, lua_upvalueindex(1), pname);
  appendcurrentpath(L, pname);              // insert the call here
  path = lua_tostring(L, -1);
  if (path == NULL)
    luaL_error(L, "'package.%s' must be a string", pname);
  return searchpath(L, name, path, ".", dirsep);
}

the path off the currently executed .lua file gets temporarily appended to path and cpath. Sure that will need some safeguarding. Would that make sense to have it in Lua?

 -Tobias




Alright. So, when using the standard Lua interpreter (`lua`), you have this global called `arg`. I forgot if it's described in the reference manual. You can use it to figure out where the file is.

Remember: `...` only includes arguments to your program, but `arg` includes the full argc, in other words all arguments to `lua`.

--
Disclaimer: these emails may be made public at any given time, with or without reason. If you don't agree with this, DO NOT REPLY.