How to get list of directories in Lua

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'

Leave a Comment