diff --git a/src/lib_package.c b/src/lib_package.c index 45a80618..48d4b140 100644 --- a/src/lib_package.c +++ b/src/lib_package.c @@ -3,7 +3,7 @@ ** Copyright (C) 2005-2011 Mike Pall. See Copyright Notice in luajit.h ** ** Major portions taken verbatim or adapted from the Lua interpreter. -** Copyright (C) 1994-2008 Lua.org, PUC-Rio. See Copyright Notice in lua.h +** Copyright (C) 1994-2011 Lua.org, PUC-Rio. See Copyright Notice in lua.h */ #define lib_package_c @@ -210,19 +210,14 @@ static const char *pushnexttemplate(lua_State *L, const char *path) return l; } -static const char *findfile(lua_State *L, const char *name, - const char *pname) +static const char *searchpath (lua_State *L, const char *name, + const char *path) { - const char *path; name = luaL_gsub(L, name, ".", LUA_DIRSEP); - lua_getfield(L, LUA_ENVIRONINDEX, pname); - path = lua_tostring(L, -1); - if (path == NULL) - luaL_error(L, LUA_QL("package.%s") " must be a string", pname); lua_pushliteral(L, ""); /* error accumulator */ while ((path = pushnexttemplate(L, path)) != NULL) { - const char *filename; - filename = luaL_gsub(L, lua_tostring(L, -1), LUA_PATH_MARK, name); + const char *filename = luaL_gsub(L, lua_tostring(L, -1), + LUA_PATH_MARK, name); lua_remove(L, -2); /* remove path template */ if (readable(filename)) /* does file exist and is readable? */ return filename; /* return that file name */ @@ -233,6 +228,29 @@ static const char *findfile(lua_State *L, const char *name, return NULL; /* not found */ } +static int lj_cf_package_searchpath(lua_State *L) +{ + const char *f = searchpath(L, luaL_checkstring(L, 1), luaL_checkstring(L, 2)); + if (f != NULL) { + return 1; + } else { /* error message is on top of the stack */ + lua_pushnil(L); + lua_insert(L, -2); + return 2; /* return nil + error message */ + } +} + +static const char *findfile(lua_State *L, const char *name, + const char *pname) +{ + const char *path; + lua_getfield(L, LUA_ENVIRONINDEX, pname); + path = lua_tostring(L, -1); + if (path == NULL) + luaL_error(L, LUA_QL("package.%s") " must be a string", pname); + return searchpath(L, name, path); +} + static void loaderror(lua_State *L, const char *filename) { luaL_error(L, "error loading module " LUA_QS " from file " LUA_QS ":\n\t%s", @@ -459,6 +477,7 @@ static void setpath(lua_State *L, const char *fieldname, const char *envname, static const luaL_Reg package_lib[] = { { "loadlib", lj_cf_package_loadlib }, + { "searchpath", lj_cf_package_searchpath }, { "seeall", lj_cf_package_seeall }, { NULL, NULL } };