Lua - 出现“尝试将数字与空值比较”错误。

a={51,31,4,22,23,45,23,43,54,22,11,34}
colors={"white","white","white","white","white","white","white","white","white","white","white","white","white","white","white","white","white"}
function try(f, catch_f)
    -- 尝试运行 f 函数,如果出现异常就执行 catch_f 函数处理异常
    local status, exception = pcall(f)
    if not status then
        catch_f(exception)
    end
end
-- 根据 yellowEndIndex、redIndex 以及 blueIndex 更新 colors 数组
function refreshColors(yellowEndIndex,redIndex,blueIndex)
    for ccnt=1,table.getn(a),1 do
        if ccnt < yellowEndIndex then
            colors[ccnt] = "yellow"
        elseif ccnt == redIndex then
            colors[ccnt] = "red"
        elseif ccnt == blueIndex then
            colors[ccnt] = "blue"
        else
            colors[ccnt] = "white"
        end
    end
end
-- 尝试执行 refreshColors() 函数,如果出现异常就打印异常信息
try(refreshColors, function(e)
    print("Error Occured - "..e)
end)
-- 第一次更新 colors 数组并输出第一个元素的值
refreshColors(1,1,1)
print(colors[1])

当调用 refreshColors() 函数时,出现了异常,并且异常信息是 "Error Occured - trial.lua:11: attempt to compare number with nil"。为什么 refreshColors() 函数中没有进行比较操作但是还是会抛出异常呢?

点赞
用户344422
用户344422

你遇到错误是因为你调用了:

try(refreshColors, function(e)
print("Error Occured - "..e)
end)

refreshColors 没有参数,因此确实为 nil

2013-02-11 21:51:23
用户108234
用户108234

错误发生在第11行,这意味着:

if ccnt < yellowEndIndex then

这里有一个与数字的比较。我们知道 ccnt 是一个数字(在循环开始时初始化),所以 yellowEndIndex 必须是 nil。1 < nil 是无意义的,所以这是一个错误。

由于错误消息以“错误发生 -”开头,我们知道它一定来自 try 函数的错误处理程序。这是有道理的。你调用:

try(refreshColors, function(e)
    print("Error Occured - "..e)
end)

然后 try 调用:

pcall(f)

其中 f 是 refreshColours。这将调用 refreshColours _没有参数_,即所有参数都初始化为 nil。当然,使用 nil 值调用 refreshColouts 将自然地尝试将 1(ccnt)与 nil(yellowEndIndex)进行比较!

您可能希望修改 try 函数如下:

function try(f, catch_f, ...)
    local status, exception = pcall(f, unpack(arg))
    if not status then
        catch_f(exception)
    end
end

这样你就可以像这样调用它:

try(refreshColours, function(e)
    print("Error Occured - "..e)
end), 1, 2, 3);

将 1、2 和 3 作为参数传递给 refreshColours。

2013-02-11 21:53:30