lua對目錄的操作主要依賴lfs庫,所以頭文件必須要require lfs。lfs庫中主要有一下的方法:
lfs.attributes(filepath [, aname]) 獲取路徑指定屬性,最常用的就是mode屬性,返回字符串為file,directory,link,socket,named pipe,等等。lfs.chdir(path) 改變當前工作目錄,成功返回true,失敗返回nil加上錯誤信息lfs.currentdir 獲取當前工作目錄,成功返回路徑,失敗為nil加上錯誤信息lfs.dir(path) 返回一個迭代器(function)和一個目錄(userdata),每次迭代器都會返回一個路徑,直到不是文件目錄為止,則迭代器返回nillfs.lock(filehandle, mode[, start[, length]])lfs.mkdir(dirname) 創建一個新目錄lfs.rmdir(dirname) 刪除一個已存在的目錄,成功返回true,失敗返回nil加上錯誤信息以lua遍歷當前目錄下所有文件為例:
require 'lfs'function getpaths(rootpath, pathes) pathes = pathes or {} for entry in lfs.dir(rootpath) do if entry ~= '.' and entry ~= '..' then local path = rootpath..'/'..entry local attr = lfs.attributes(path) assert(type(attr) == 'table') if attr.mode == 'directory' then getpaths(path, pathes) else table.insert(pathes, path) end end end return pathesendpathes = {}getpaths('.', pathes)PRint(#(pathes))for i = 1, #(pathes) do print(pathes[i])end新聞熱點
疑難解答