-2

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
frankpujo
  • 125
  • 9

1 Answers1

2
    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
lejlot
  • 64,777
  • 8
  • 131
  • 164
  • Thank you for your answer, realized now how lame of a mistake it was. I'm going to use the first one as I still need it to move to the next, and therefore require for the counter to increment before the movement is made. Thanks again. – frankpujo Jan 26 '22 at 20:58