Lua - “尝试将数字与nil进行比较”错误

时间:2013-02-11 21:45:09

标签: exception lua null

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)
    local status, exception = pcall(f)
    if not status then
        catch_f(exception)
    end
end
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
try(refreshColors, function(e)
    print("Error Occured - "..e)
end)
refreshColors(1,1,1)
print(colors[1])

当调用refreshColors()函数时,它会抛出异常并且错误消息是“Error Occured - trial.lua:11:尝试将数字与nil进行比较”。尽管在refreshColors()函数中没有这样的比较,为什么会发生异常?

2 个答案:

答案 0 :(得分:8)

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

if ccnt < yellowEndIndex then

你与一个数字进行比较。我们知道ccnt是一个数字(它在循环开始时初始化),所以yellowEndIndex必须是nil。 1&lt; nil 是胡说八道,所以这是一个错误。

由于错误消息以“Error Occured - ”开头,我们知道它必须来自您的 try 函数错误处理程序。这是有道理的。你打电话:

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

然后尝试调用:

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。

答案 1 :(得分:1)

是否因为您正在呼叫而发生错误:

尝试(refreshColors,函数(e)     打印(“错误发生 - ”..e) 端)

并且,refreshColors没有参数,所以它确实是零?