Lua for循环无法正常迭代。

我非常需要关于for循环的帮助。我正在尝试在Lua和Corona SDK中进行for循环,但我做错了什么,但我不知道是什么。请参阅以下我的代码:

function moveLift(event)
    for j=1,4,1 do
        if event.phase == "began" then
            markY = event.target.y

        elseif event.phase == "moved" then
            local y = (event.y - event.yStart) + markY
            event.target.y = y

        elseif event.phase == "ended" then

            if (hasCollided( event.target, hotSpots[j] )) then

                print("hasCollided with floor: ", hotSpots[j].floor)

                if (event.target.destination == hotSpots[j].floor) then
                    print("correct floor")
                    succesfullPassengers = succesfullPassengers + 1

                    if succesfullPassengers == PASSENGER_AMOUNT then
                        print("game over")
                    end
                else
                    print("Wrong! elevator has collided with floor: ", hotSpots[j].floor)
                end
            end
        end
        return true
    end
end

我想做的是检查当我在屏幕上拖放电梯时它停在哪个楼层上。我创建了热点(基本上是命中框架,目前充当艺术占位符),并将它们放置在hotSpot表中,例如:

-- Create elevator hotspots
for k=1,4,1 do
    hotSpots[k] = display.newRect( gameAreaGroup, 0, 0, 50, 75 )
    hotSpots[k].alpha = 0.25  --Show hotspots with alpha
    hotSpots[k].floor = k -- The floor id
    print("Created hotspot on floor: ",hotSpots[k].floor)
    hotSpots[k].x = display.contentWidth *0.5
    hotSpots[k].y = firstFloor - (FLOOR_HEIGHT * k)
    hotSpots[k]:setFillColor( 255,0,0 )
    hotSpots[k]:addEventListener( "tap", returnFloor ) -- Check floor value
    gameAreaGroup:insert(hotSpots[k])
end

我使用一个名为returnFloor的测试函数检查每个热点是否具有唯一的楼层值,它们(1,2,3,4)已经具有了。当我在第一层拖放电梯时,我收到消息“Wrong!elevator has collided with floor:1”,但在其他任何楼层,我会收到消息:“hasCollided with floor:1”。所以在moveLift函数中的for循环中肯定有问题,因为它只返回楼层1而不返回任何其他楼层。

PS:正确的楼层是4,顶层。

点赞
用户3828960
用户3828960

你在 for 循环中放置了 "return true",所以它永远不会超过 j=1。我认为你需要把这个语句移到最后一个 if 语句的内部,或者将其放置在随后的 "end" 下面(如果不知道完整逻辑,我不确定返回值的用途)。

2014-10-28 19:59:56
用户869951
用户869951

最后的代码行应该是 end end end return true end 而不是 end end return true end end,这样返回语句就能在循环完成后执行。

2014-10-28 20:57:05