new function 'package.searchpath'

This commit is contained in:
Roberto Ierusalimschy 2007-12-12 12:36:12 -02:00
parent dae850e0ee
commit bc82b4d78a
1 changed files with 29 additions and 11 deletions

View File

@ -1,5 +1,5 @@
/*
** $Id: loadlib.c,v 1.57 2007/03/26 15:57:35 roberto Exp roberto $
** $Id: loadlib.c,v 1.58 2007/06/21 13:52:27 roberto Exp roberto $
** Dynamic library loader for Lua
** See Copyright Notice in lua.h
**
@ -346,18 +346,12 @@ static const char *pushnexttemplate (lua_State *L, const char *path) {
}
static const char *findfile (lua_State *L, const char *name,
const char *pname) {
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);
static const char *searchpath (lua_State *L, const char *name,
const char *path) {
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 */
@ -369,6 +363,29 @@ static const char *findfile (lua_State *L, const char *name,
}
static int ll_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;
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);
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",
lua_tostring(L, 1), filename, lua_tostring(L, -1));
@ -604,6 +621,7 @@ static void setpath (lua_State *L, const char *fieldname, const char *envname,
static const luaL_Reg pk_funcs[] = {
{"loadlib", ll_loadlib},
{"searchpath", ll_searchpath},
{"seeall", ll_seeall},
{NULL, NULL}
};