How to get list of directories in Lua

前端 未结 8 1908
离开以前
离开以前 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

    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).

    0 讨论(0)
  • 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'
    
    0 讨论(0)
提交回复
热议问题