How to get list of directories in Lua

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

    Don't parse ls, it's evil! Use find with zero-terminated strings instead (on linux):

    function scandir(directory)
        local i, t = 0, {}
        local pfile = assert(io.popen(("find '%s' -maxdepth 1 -print0"):format(directory), 'r'))
        local list = pfile:read('*a')
        pfile:close()
        for filename in s:gmatch('[^\0]+')
            i = i + 1
            t[i] = filename
        end
        return t
    end
    

    WARNING: however, as an acceped answer this apporach could be exploited if directory name contain ' in it. Only one safe solution is to use lfs or other special library.

提交回复
热议问题