How to get list of directories in Lua

 for dir in io.popen([[dir "C:\Program Files\" /b /ad]]):lines() do print(dir) end

*For Windows

Outputs:

Adobe
Bitcasa
Bonjour
Business Objects
Common Files
DVD Maker
IIS
Internet Explorer
iPod
iTunes
Java
Microsoft Device Emulator
Microsoft Help Viewer
Microsoft IntelliPoint
Microsoft IntelliType Pro
Microsoft Office
Microsoft SDKs
Microsoft Security Client
Microsoft SQL Server
Microsoft SQL Server Compact Edition
Microsoft Sync Framework
Microsoft Synchronization Services
Microsoft Visual Studio 10.0
Microsoft Visual Studio 9.0
Microsoft.NET
MSBuild
...

Each time through the loop you are given a new folder name. I chose to print it as an example.


Take the easy way, install lfs. Then use the following constructs to find what you need:

require'lfs'
for file in lfs.dir[[C:\Program Files]] do
    if lfs.attributes(file,"mode") == "file" then print("found file, "..file)
    elseif lfs.attributes(file,"mode")== "directory" then print("found dir, "..file," containing:")
        for l in lfs.dir("C:\\Program Files\\"..file) do
             print("",l)
        end
    end
end

notice that a backslash equals [[\]] equals "\\", and that in windows / is also allowed if not used on the cmd itself (correct me if I'm wrong on this one).


I hate having to install libraries (especially those that want me to use installer packages to install them). If you're looking for a clean solution for a directory listing on an absolute path in Lua, look no further.

Building on the answer that sylvanaar provided, I created a function that returns an array of all the files for a given directory (absolute path required). This is my preferred implementation, as it works on all my machines.

-- Lua implementation of PHP scandir function
function scandir(directory)
    local i, t, popen = 0, {}, io.popen
    local pfile = popen('ls -a "'..directory..'"')
    for filename in pfile:lines() do
        i = i + 1
        t[i] = filename
    end
    pfile:close()
    return t
end

If you are using Windows, you'll need to have a bash client installed so that the 'ls' command will work - alternately, you can use the dir command that sylvanaar provided:

'dir "'..directory..'" /b /ad'