Pit Lib Directory Stuff

lua-users home
wiki

Here are some directory traversal functions as part of PetersStdLib. Note that they are Win32-only so far and need the little C-Function at the end to work. (though it should be easy to provide functions for any other OS you like) It might also be a good idea to use the posix-library for this. (see also: StandardLibraryProposal)

Directory Code

-- 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.


RecentChanges · preferences
edit · history
Last edited April 8, 2007 2:36 am GMT (diff)