简体   繁体   中英

Lua function returning error after false "if statement"

I have a function to move a point over to different positions. I have a positions table containing all the Xs and Ys of each position, a position counter ( posCounter ) do keep track of where the point is and a maxPos , which is pretty much the lenght of the table positions .
In this code snippet, everything after if posCounter <= maxPos then shouldn't run if the posCounter variable is greater than 3, but I still get an error for exceeding the table's limit.

local maxPos = 3
local posCounter = 1
local function movePointToNext( event )
    if posCounter <= maxPos then
        posCounter = posCounter + 1
        transition.to( pointOnMap, { x = positions[posCounter].x, y = positions[posCounter].y } )
    end
end
    if posCounter <= maxPos then
        posCounter = posCounter + 1

What happens if posCounter == maxPos? Your if executes, then you increment it , so it is too big (equal to maxPos + 1), and then you try to index with it, thus giving you an error.

You either want to change your if to stop at posCounter == maxPos - 1, so that after incrementing it still is correct; or you want to move your increment after indexing with it (depending on what is the intended behaviour of your code).

option 1

local maxPos = 3
local posCounter = 1
local function movePointToNext( event )
    if posCounter < maxPos then
        posCounter = posCounter + 1
        transition.to( pointOnMap, { 
            x = positions[posCounter].x, 
            y = positions[posCounter].y } )
    end
end

option 2

local maxPos = 3
local posCounter = 1
local function movePointToNext( event )
    if posCounter <= maxPos then
        transition.to( pointOnMap, { 
            x = positions[posCounter].x, 
            y = positions[posCounter].y } )
        posCounter = posCounter + 1
    end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM