Lua   发布时间:2022-04-11  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了异常 – Lua – “尝试将数字与nil进行比较”错误大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
a={51,31,4,22,23,45,43,54,11,34}
colors={"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()函数中没有这样的比较,为什么会发生异常?

解决方法

错误在第11行,这意味着:
if ccnt < yellowEndIndex then

你有一个数字的比较.我们知道ccnt是一个数字(它在循环开始时初始化),所以yellowEndIndex必须是nil. 1<零是无稽之谈,所以这是一个错误. 由于错误消息以“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),2,3);

将1,2和3作为参数传递给refreshColours.

大佬总结

以上是大佬教程为你收集整理的异常 – Lua – “尝试将数字与nil进行比较”错误全部内容,希望文章能够帮你解决异常 – Lua – “尝试将数字与nil进行比较”错误所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。