[英]Attempt to compare nil with number Error in Lua (Corona Lab)
我是Corona(Lua)的新手。 运行游戏后,游戏似乎运行良好,直到几秒钟后出现以下错误:“尝试将nil与数字进行比较”
局部函数gameLoop()
-- create new asteroids
createAsteroid()
-- remove asteroids which have been drifted off the screen
for i = #asteroidsTable, 1, -1 do
local thisAsteroid = asteroidsTable [i]
if (thisAsteroid.x < -100 or
thisAsteroid.x > display.contentWidth + 100 or
thisAsteroid.y < -100 or
thisAsteroid.y > display.contentHeight + 100 )
then
display.remove( thisAsteroid )
table.remove( asteroidsTable)
end
end
结束
如上所示,“ thisAsteroid”位于“ asteroidsTable = {}”中,它被定义为模块顶部的变量,且位于任何函数的外部。
局部小行星表= {}
谢谢你的帮助!
thisAsteroid.x
, thisAsteroid.y
, display.contentWidth
或display.contentHeight
为nil
。
使用print(thisAsteroid.x)
等找出哪个是nil
。
您还应该获得带有错误消息的行号,以帮助您发现问题。
一旦找到nil
值,就必须防止它变为nil
或者如果不能这样做,则应将比较范围限制为非nil
值。
尝试
-- create new asteroids
createAsteroid()
-- remove asteroids which have been drifted off the screen
for i = #asteroidsTable, 1, -1 do
local asteroid = asteroidsTable [i]
if (asteroid.x < -100 or
asteroid.x > display.contentWidth + 100 or
asteroid.y < -100 or
asteroid.y > display.contentHeight + 100 )
then
local asteroidToRemove = table.remove(asteroidsTable, i)
if asteroidToRemove ~= nil then
display.remove(asteroidToRemove)
asteroidToRemove= nil
end
end
end
end
来自lua.org 文档
table.remove(列表[,pos])
从列表中删除位置pos上的元素,返回已删除元素的值。 当pos是1到#list之间的整数时,它将下移元素list [pos + 1],list [pos + 2],...,list [#list]并擦除元素list [#list]; 当#list为0或#list + 1时,索引pos也可以为0。 在这种情况下,该函数将删除元素列表[pos]。
pos的默认值为#list,因此调用表。remove(l)删除列表l的最后一个元素。
因此,使用指令table.remove(asteroidsTable)
可以从表asteroidsTable
删除最后一个元素,但是应该删除第i个元素。
在Corona 论坛上了解有关从表中删除元素的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.