不使用Lua的lfs库去遍历一个目录

要想不使用Lua的lfs库,唯一的办法就是使用操作系统提供的命令

首先定义一个遍历目录的函数:

local function traverseFiles(dir)
  local cmd = string.format('dir "%s" /b /s', dir)
  local handle = io.popen(cmd, 'r')
  local result = handle:read("*a")
  handle:close()

  local files = {}
  for file in result:gmatch("[^\r\n]+") do
    if not file:match("^[.]$") and not file:match("^[.][.]$") then
      table.insert(files, file)
    end
  end

  return files
end
倘若使用了别人封装的lua引擎,对read函数做了防溢出操作,不允许进行read(“*a”)操作时,可以做如下尝试
local function traverseFiles(dir)
	local cmd = string.format('dir "%s" /b /s', dir)
	local handle = io.popen(cmd, 'r')	
	
	if(handle == nil) then
		log_w("open file for dir fail")
		return
	end
	
	local files = {}
	for file in handle:lines() do
		if not file:match("^[.]$") and not file:match("^[.][.]$") then
		table.insert(files, file)
		end
	end
	
	handle:close()

  return files
end

返回的files便可以为所欲为了

for i, file in ipairs(cachefiles) do 
	os.remove(file)
end
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值