lua-users home
lua-l archive

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



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