Lua Recipes

lua-users home
wiki

Here's various ways to do things.

Getting a list of files or directories

The standard version of Lua does not itself contain a portable method to obtain a list of files or directories from your file system. The reason is that, for portability, Lua restricts itself to ANSI C, which itself does not provide this capability. These capabilities are, however, often available through the operating system (e.g. readdir on POSIX, _findfirst / _findnext on VC/Windows, or FindFirstFile/FindNextFile on plain Win32 (kernel32.dll)). These can be accessed through extension libraries or even os.execute calls to the shell.

There are a few Lua extension libraries that provide similar functions. The ExtensionProposal API has Windows and POSIX implementations of os.dir. As of version 1.2, LuaFileSystem [1] has an lfs.dir function. There is a readdir in lua-fs [2], but that uses the POSIX readdir at the time of this writing (2007). See also PitLibDirectoryStuff.

Some less-than portable hacks are possible via the OS shell--os.execute call. See the io.readDir function for UNIX in stdlib [3]. This approach is somewhat inefficient as it involves process creation.

It would also be possible to use the POSIX readdir on non-POSIX systems through an emulation function. There are Win32 emulations of the POSIX readdir and friends [4] [5]. See also mingwex/direct.c in mingw-runtime [6].

Another option is to use Python's os.listdir() via Lunatic Python [7] as shown below.

require "python"
pg = python.globals()
pos = pg.import("os")
x = pos.listdir(".")
print(x)

Lua 5.1.

--DavidManura


Note: Some content was moved to MakingLuaLikePhp.


RecentChanges · preferences
edit · history
Last edited September 26, 2010 4:21 am GMT (diff)