运行失败,但调试正常。

我有以下3个函数:

function getName() -- 返回没有扩展的文件名
    local files = scandir(currentDir())
    local name = nil

    for i = 1, #files do
        if isValidExt( getExt(files[i]) ) then
            name = getFilename(files[i])
            break
        end
    end

    return name
end
function currentDir()
    local string = debug.getinfo(1).source
    local endPoint = getLastOcurrence(string, '/')
    local dir = string.sub(string, 2, endPoint)
    return dir
end
function getLastOcurrence(str, char)
    local last = string.find(string.reverse(str), char, 1, true)
    return #str - last
end

奇怪的是,调试没有问题,而运行时却报错:

...\Downloader.lua:22: attempt to perform arithmetic on local 'last' (a nil value)
stack traceback:
...\Downloader.lua:22: in function 'getLastOcurrence'
...\Downloader.lua:39: in function 'currentDir'
...\Downloader.lua:50: in function 'getName'

是什么原因导致调试和运行之间的差异?

点赞
用户204011
用户204011

我的猜测是,当您不在调试模式时,您会编译代码并删除调试信息,因此 debug.getinfo(1).source 不是文件名(也不包含 / 字符)。尝试在 currentDir() 函数中打印其值。

2013-09-16 10:18:24