【发布时间】:2014-07-04 10:45:52
【问题描述】:
我在 main.lua 中有以下代码 我要做的就是生成矩形,将它们添加到物理中,这样它们就可以从屏幕上掉下来,一旦它们的 y 大于屏幕高度(意味着它们不再可见),就从内存中删除矩形,并删除那些矩形被用户触摸。
这是我的代码
local physics = require( "physics")
physics.start( )
--table to hold dynamically created rectangles
local rects={}
--used as index for table
local numRect=0
--event handler for rectangle touch
local function rectTouch(event)
event.target:removeSelf( )
event.target = nil
end
--function for spawning rectangles
local function spawnRect()
numRect = numRect + 1
rects[numRect] = display.newRect( display.contentWidth/2, 200, 200, 200)
rects[numRect]:setFillColor( 1,1,1 )
physics.addBody( rects[numRect], "dynamic",{density=1, friction=0,2, bounce=0 })
rects[numRect]:addEventListener( "touch", rectTouch )
end
--function for removing rectangles which are no more visible
local function removeInactiveRects()
for i = 1, #rects do
if rects[i] ~= nil then
if rects[i].y > display.contentHeight + 100 then
rects[i]:removeSelf( )
rects[i] = nil
end
end
end
end
timer.performWithDelay( 1000, spawnRect, -1 )
timer.performWithDelay( 2000, removeInactiveRects,-1 )
我收到一个错误 removeInactiveRects 函数,指出尝试将数字与 nil 进行比较,我猜负责此的语句是 rects[i] ~= nil 但我不知道为什么。此外,它是从内存中删除对象的正确方法吗?
【问题讨论】:
-
5 ~= nil是法律声明。该错误可能来自rects[i].y > display.contentHeight + 100比较。这意味着您的rects[i]对象此时没有y值。 -
是的.. 我评论了那行,似乎是
rects[i].y > display.contentHeight + 100导致了问题。但我不明白为什么在 rectTouch() 中我要删除对象并将其设为 nil,并且条件if rects[i] ~= nil then不应该允许它达到if rects[i].y > display.contentHeight + 100 then如果它是 nil