Pit Lib Directory Stuff |
|
-- 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
Here is Dirk Ringes implementation of the Read-Directory function that i used for these functions in the 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; }
See also LuaRecipes for more detailed info on accessing file/directory listings from Lua.