Lua - 出现“尝试将数字与空值比较”错误。
2013-2-11 21:45:9
收藏:0
阅读:150
评论:2
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() 函数中没有进行比较操作但是还是会抛出异常呢?
点赞
用户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
评论区的留言会收到邮件通知哦~
推荐文章
- 如何将两个不同的lua文件合成一个 东西有点长 大佬请耐心看完 我是小白研究几天了都没搞定
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?
- addEventListener 返回 nil Lua
- Lua中获取用户配置主目录的跨平台方法
你遇到错误是因为你调用了:
try(refreshColors, function(e) print("Error Occured - "..e) end)而
refreshColors没有参数,因此确实为nil?