How to get list of directories in Lua

前端 未结 8 1905
离开以前
离开以前 2020-12-01 03:46

I need a list of directory in LUA

Suppose I have a directory path as "C:\\Program Files"

I need a list of all the folders in that particular path and

8条回答
  •  春和景丽
    2020-12-01 04:28

    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'
    

提交回复
热议问题