Lua function returning error after false "if statement"

38 Views Asked by At

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
1

There are 1 best solutions below

1
lejlot On BEST ANSWER
    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