为什么这个递归函数的参数为nil?

walk 是一个递归函数,它遍历给定的树,如果遍历到文件,则对其执行某些操作。 这个“执行某些操作”应该进行更改。 我可以在 walk 中使用 coroutine.yield(f),但我想先了解自己的错误在哪里。

如你所见,参数 lootfunc 是通过引用给出的,应在 walk 中调用它。 但是它给出了下面看到的错误。那么参数 lootfunc 为什么是空的呢?

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

local function loot(d)
  if MATCH == "path" then  -- 只查看路径而不是内容
    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) -- 下一轮
              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]: ?
点赞
用户1009479
用户1009479

你正在函数 walk 中调用 walk(f),只有一个参数,第二个参数填充了 nil,所以更改:

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

if attr.mode == "directory" then
     walk(f, lootfunc) -- next round
2014-09-03 08:42:16