Lua 函数 findFilePath 中 local counts 变量未重置导致递归调用错误的解决方法

在 Lua 函数 findFilePath 中,由于 local counts 变量未在每次调用时重置为 0,导致其在递归调用过程中累计,最终可能导致 counts 超过 count,进而无法进入递归调用。

原始代码:

local counts = 0
function findFilePath(path,compare,count,counts)
    if counts > count then
        return nil
    end

    local rd = ms.os.read_dir(path)
    local data
    if rd or next(rd) then
        for index, fileInfo in pairs(rd) do
            local destTarget = path .. '/' .. fileInfo.name
            -- print("destTarget : ".. destTarget)
            if fileInfo.is_dir then
                counts = counts+1
                data = findFilePath(destTarget,compare,counts)
                if data ~= nil then
                    return data
                end

            elseif  fileInfo.is_dir  == false then
                if ms.strings.contains(destTarget,compare)   then
                    if utils.fileExist(destTarget) == true then

                        print("destTarget : " .. destTarget)
                        data = destTarget
                        break

                    end
                end
            end
        end

        if data ~= nil then
            return data
        end
    end
end

解决方法:

将 counts 作为参数传递给 findFilePath 函数,每次调用时都传入初始值 0。

function findFilePath(path, compare, count, counts)
    counts = counts or 0  -- 如果未传入 counts,则将其默认为 0
    if counts > count then
        return nil
    end

    local rd = ms.os.read_dir(path)
    local data
    if rd or next(rd) then
        for index, fileInfo in pairs(rd) do
            local destTarget = path .. '/' .. fileInfo.name
            -- print('destTarget : '.. destTarget)
            if fileInfo.is_dir then
                counts = counts + 1
                data = findFilePath(destTarget, compare, count, counts)
                if data ~= nil then
                    return data
                end
            elseif fileInfo.is_dir == false then
                if ms.strings.contains(destTarget, compare) then
                    if utils.fileExist(destTarget) == true then
                        print('destTarget : ' .. destTarget)
                        data = destTarget
                        break
                    end
                end
            end
        end
        if data ~= nil then
            return data
        end
    end
end

解释:

  1. counts 作为参数传入函数,并将其设置为可选参数。
  2. 在函数开头使用 counts = counts or 0 来判断 counts 是否存在,如果不存在,则将其设置为 0。

这样,每次调用 findFilePath 函数时,都会将 counts 重置为 0,确保计数器不会累计,从而避免递归调用错误。

总结:

通过将 counts 作为参数传递,并将其在每次调用时重置为 0,可以有效解决 Lua 函数 findFilePath 中 local counts 变量未重置导致的递归调用错误问题。这种方法简单易懂,易于实现,同时能够保证函数的正确执行。

Lua 函数 findFilePath 中 local counts 变量未重置导致递归调用错误的解决方法

原文地址: https://www.cveoy.top/t/topic/m9RU 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录