我需要 LUA 中的目录列表
假设我的目录路径为“C:\Program Files”
我需要该特定路径中所有文件夹的列表以及如何搜索该列表中的任何特定文件夹。
Example
需要路径“C:\Program Files”中所有文件夹的列表
以下是上述路径中的文件夹名称
-
test123
-
test4567
-
文件夹 123
-
文件夹 456
-
文件夹 456 789
需要在列表中获取上述内容,然后必须仅在文件夹 456 789 中搜索特定字符串,例如文件夹 456。
已尝试过以下代码。下面我缺少的东西:-
local function Loc_Lines( str )
--
local ret= {} -- 0 lines
while str do
local _,_,line,tail= string.find( str, "(.-)\n(.+)" )
table.insert( ret, line or str )
str= tail
Print (str)
end
return ret
end
local function Loc_ShellCommand( cmd )
--
local str= nil
--
local f= io.popen( cmd ) -- no command still returns a handle :(
if f then
str= f:read'*a'
Print(str)
f:close()
end
if str=="" then -- take no output as a failure (we can't tell..)
Print("hi")
str= nil
end
-- Remove terminating linefeed, if any (eases up one-line analysis)
--
if str then
if string.sub( str, -1 ) == '\n' then
str= string.sub( str, 1, -2 )
end
end
return str
end
local function Loc_DirCmd( cmd )
Print(cmd)
local str= Loc_ShellCommand( cmd )
return Loc_Lines(str)
end
local function Loc_DirList( dirname )
local ret= {}
local lookup= {}
local tbl= Loc_DirCmd( "dir /AD /B "..dirname ) -- only dirs
-- Add slash to every dir line
--
for i,v in ipairs(tbl) do
table.insert( ret, v..'\\' )
lookup[v]= true
end
-- Return with forward slashes
--
if true then
for i=1,table.getn(ret) do
ret[i]= string.gsub( ret[i], '\\', '/' )
Print (ret[i])
end
end
return ret
end
Loc_DirList("C:\\Program Files\\")
我讨厌必须安装库(尤其是那些希望我使用安装程序包来安装它们的库)。如果您正在寻找一个干净的解决方案来在 Lua 中的绝对路径上列出目录,那么就不用再犹豫了。
基于 sylvanaar 提供的答案,我创建了一个函数,该函数返回给定目录的所有文件的数组(需要绝对路径)。这是我的首选实现,因为它适用于我的所有机器。
-- 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
如果您使用的是 Windows,则需要安装 bash 客户端,以便“ls”命令正常工作 - 或者,您可以使用 sylvanaar 提供的 dir 命令:
'dir "'..directory..'" /b /ad'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)