Question Details

No question body available.

Tags

lua directory

Answers (3)

April 19, 2025 Score: 4 Rep: 27,084 Quality: Medium Completeness: 80%

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

April 18, 2025 Score: 2 Rep: 10,496 Quality: Low Completeness: 50%

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.

May 3, 2025 Score: 0 Rep: 1 Quality: Low Completeness: 40%

You could use the io.popenfunction to run a OS command, in linux you can run ls -1 then get the output of the executed command.

local files = io.popen("ls -1")

the -1 is to list only the file names per line