首页 > 学院 > 开发设计 > 正文

lua目录操作

2019-11-08 03:22:22
字体:
来源:转载
供稿:网友

Lua 目录操作

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
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表