Pit Lib Directory Stuff |
|
|
----- There are Win32 emulations of the POSIX readdir and friends. [1] [2]. See also mingwex/direct.c in mingw-runtime [3]. Unfortunately (as of version 1.2), LuaFileSystem [4] does not implement a readdir, though there is one in lua-fs [5], but that uses the POSIX readdir.Some less-than portable hacks are possible via the OS shell only (see Windows-version dir on page by PeterOdding) or the similar UNIX-version io.readDir in stdlib [6]. This approach is somewhat inefficient as it involves process creation. It might be nice to combine those two into a function that would work on both UNIX and Windows.Another option is to use Python's {os.listdir()} via Lunatic Python [7] as shown below.
--DavidManura Please note that LuaFilesystem? does indeed have a directory iterator lfs.dir().There is also the ExtensionProposal API which has implementations for Windows and POSIX systems and provides os.dir() among other functions.--MarkEdgar |
|
See also LuaRecipes for more detailed info on accessing file/directory listings from Lua. |
-- 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.