How to list or iterate directory contents in Lua? E.g. for a directory /home/user
, I should see /home/user/Desktop
, /home/user/Downloads
etc.
Ideally no external libraries should be used; or as few as possible.
Lua has very limited file system support in its standard library, because it is largely a wrapper around the standard C library, which itself has lackluster filesystem support. os.rename
, os.remove
, os.tmpname
, io.tmpfile
are all direct analogues to their standard C counterpart.
As pointed out, io.popen
is available1 to POSIX systems (popen
), as well as Windows (_popen
), which can be used to invoke platform-dependent tools.
Not the ideal case, but LuaFileSystem can be used if you are comfortable with including one additional external library in your project. LFS has support for Linux / BSD / macOS and Windows, and provides the usual filesystem operations (complementing those already found in the standard library).
Minimal example of iterating through a directory:
local lfs = require 'lfs'
for entry in lfs.dir '/sys' do
print(entry)
end
.
..
kernel
power
class
devices
dev
hypervisor
fs
bus
firmware
block
module
Ideally, if the project calls for it, you may want to drop down to the C API and use library and system calls to implement the level of support needed for your particular platform(s).
1. Lua 5.4.7 liolib.c source file, including the definition of the cross-platform l_popen
macro.
There seem to be no cross-platform way for that as of Lua-5.4.7 (2025).
As a work-around, on Linux and Mac:
for file in io.popen("ls -- /home/user"):lines() do
print(file)
end
Or on Windows, something like:
for file in io.popen('dir "C:/something" /b'):lines() do
print(file)
end
With this approach, you execute ls -- /home/user
and read its output line by line.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With