lua使用io.open跨平台文件夾遍歷匹配查找


  -- Desc :實現在LUA_PATH中的lua文件中遍歷尋找沒用到PNG_PATH路徑下的png圖片,並將其打印出來。
-- Date :12:49:28 2014-09-04
1 print
("Lua Script Start") 2 3 function getFileName( path ) 4 len = string.len(PNG_PATH); 5 return string.sub(path, len+2) --  remove "/" 6 end 7 8 function isInIt( file,name ) 9 --print(file .. " -- " .. name ) 10 for line in io.lines(file) do 11 if isContain(line , name) then 12 return true; 13 end 14 end 15 return false; 16 end 17 18 function isContain( line , str ) 19 return string.find(line , str); 20 end 21 22 PNG_PATH = "user/image" 23 getPngFileTable = io.popen('find * ' .. PNG_PATH) 24 25 pngFileTable = {}; 26 for file in getPngFileTable:lines() do 27 if string.find(file,"%.png$") then 28 fileName = getFileName(file); 29 print(fileName) 30 table.insert(pngFileTable,fileName); 31 end 32 end 33 print("png count is :"..#pngFileTable); 34 35 LUA_PATH = "user/scripts" 36 getLuaFileInfo = io.popen('find * ' .. LUA_PATH) 37 luaFileTable = {}; 38 for file in getLuaFileInfo:lines() do 39 if string.find(file,"%.lua$") then 40 --print(file) 41 table.insert(luaFileTable,file); 42 end 43 end 44 45 local pairs = pairs 46 for _,name in pairs(pngFileTable) do 47 flag = 0; 48 for _,file in pairs(luaFileTable) do 49 if isInIt(file , name) then 50 flag = 1; 51 break; 52 end 53 end 54 if flag == 0 then 55 print(name) 56 end 57 end 58 59 print("Lua Script End!") 60 61 --Desc: lua io.popen ([prog [, mode]]) 62 --Starts program prog in a separated process and returns a file handle that 63 --you can use to read data from this program (if mode is "r", the default) 64 --or to write data to this program (if mode is "w"). 65 --This function is system dependent and is not available on all platforms.

注:

1: io.popen()簡易說明  Lua中,os.execute可以執行dos命令,但是返回的是系統狀態碼,默認輸出

      io.popen()也可以執行dos命令,但是返回一個文件。eg:

  local t = io.popen('svn help')

  local a = t:read("*all")   --a返回一個字符串,內容是svn help的內容

  如果想執行某命令或程序可選os.execute() , 如果還想捕捉該執行結果可用io.popen(),得到的是userdata數據類型;

  eg:復制文件 os.execute("copy" .. originalPath .. "," .. backupPath)

2: io.popen() 是跨平台的,卻也跟系統有關,在windows下無法取得訪問文件夾的權限,屢次嘗試都沒成功,liunx和mac下可以;

3: 目前還不得知,使用io.poen()遍歷的png圖片竟然會 遍歷了兩邊,造成結果是一半為臟數據,記載此文時還在查找原因,不解啊;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM