Pit Lib 目录操作 |
|
-- dofile for every lua file in folder function dodirectory(directory, mask) mask = mask or "*.lua" -- default extension is lua local list = External_ReadDirectory(directory.."\\"..mask) local i=1 sort(list) while list[i] do dofile(directory.."\\"..list[i]) i=i+1 end end -- user function for every file in (current) folder -- example: fordirectory(print) or fordirectory(dofile, "*.lua") -- or fordirectory(execute, "*.bat", "C:\\") function fordirectory(f, mask, directory) local prefix = "" -- default folder is current folder if directory then prefix = directory.."\\" end mask = mask or "*.*" -- default mask is "all files with extension" local list = External_ReadDirectory(prefix..mask) local i=1 sort(list) while list[i] do f(prefix..list[i]) i=i+1 end end
以下是 Dirk Ringes 实现的 Read-Directory 函数,我在 stdlib 中的这些函数中使用了它
#include "io.h" static int External_ReadDirectory(lua_State* pLuaState) { const char *mask; struct _finddata_t c_file; long hFile; int i = 1; if(lua_isstring(pLuaState, 1)) mask = lua_tostring(pLuaState, 1); else mask = "*.*"; lua_newtable(pLuaState); hFile = _findfirst(mask, &c_file); if(hFile != -1) { lua_pushstring(pLuaState, c_file.name); lua_rawseti(pLuaState, -2, i); while(_findnext(hFile, &c_file) == 0) { i ++; lua_pushstring(pLuaState, c_file.name); lua_rawseti(pLuaState, -2, i); } _findclose(hFile); } return 1; }
另请参阅 LuaRecipes,以获取有关从 Lua 访问文件/目录列表的更详细的信息。