2014-09-03 67 views
2

walk是一個遞歸函數,它可以遍歷給定的樹,並且如果遍歷文件對它做些什麼。 應該改變「用它做什麼」。 我可以在步行中使用coroutine.yield(f),但我首先想知道我的錯誤。爲什麼這個遞歸函數參數nil?

正如您所見,參數lootfunc由參考文獻給出,應在walk內調用。 但它給了我下面看到的錯誤。那麼爲什麼參數lootfuncnil

local KEYWORDS = { 
     "%.db[x]?", 
     "%.ojsn", 
} 


local function loot(d) 
    if MATCH == "path" then -- only look to the path not to the content 
    for i,keyword in pairs(KEYWORDS) do 
     if string.find(d,keyword) then 
     --coroutine.yield(d) 
     print(d) 
     end 
    end 
    end  
end 

local function walk (path,lootfunc) 
    for file in lfs.dir(path) do 
     if file ~= "." and file ~= ".." then 
      local f = path..'/'..file 
      local attr = lfs.attributes (f) 
      if(type(attr) == "table") then 
       if attr.mode == "directory" then 
        walk (f) -- next round 
       elseif attr.mode == "file" then 
        lootfunc(f) 
       end 
      end 
     end 
    end 
    end 

walk("/path/",loot) 

shadowed.lua:73: attempt to call local 'lootfunc' (a nil value) 
stack traceback: 
    (command line):1: in function 'lootfunc' 
    shadowed.lua:73: in function 'walk' 
    shadowed.lua:71: in function 'walk' 
    shadowed.lua:71: in function 'walk' 
    shadowed.lua:88: in main chunk 
    [C]: in function 'dofile' 
    (command line):1: in function <(command line):1> 
    [C]: in function 'xpcall' 
    (command line):1: in main chunk 
    [C]: ? 

回答

4

要調用的函數walkwalk(f),只有一個參數,第二個參數填充nil,所以更改:

if attr.mode == "directory" then 
    walk(f) -- next round 

if attr.mode == "directory" then 
    walk(f, lootfunc) -- next round