【问题标题】:Why is this recursion function parameter nil?为什么这个递归函数参数为零?
【发布时间】:2014-09-03 08:17:18
【问题描述】:

walk 是一个递归函数,它遍历给定的树,如果遍历一个文件,则对其进行处理。 “用它做点什么”应该改变。 我可以在 walk 中使用coroutine.yield(f),但我想先知道我的错误。

如您所见,参数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]: ?

【问题讨论】:

    标签: recursion lua


    【解决方案1】:

    你在函数walk中调用walk(f),只有一个参数,第二个参数是nil,所以改一下:

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

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

    【讨论】:

      猜你喜欢
      • 2020-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-03
      • 1970-01-01
      相关资源
      最近更新 更多