Chris
Chris

Reputation: 4372

table.remove ends in position out of bounds

So I'm trying to remove an element from my array, but I always end up in an exception:

bad argument #1 to 'remove' (position out of bounds)

Here is the code:

    -- setup players
    players = {}
    for i=0, 3 do
        local gp = InputHandler:gamepad(i)
        if(gp:isConnected()) then
            logMessage(i .. " is connected")
            players[i] = createCharacter(i, gp)
        end
    end

-- ....

-- update players
for k, player in pairs(players) do
    logMessage("player index: " .. k)

    -- if update returns false, the played lost all lives
    if (player.update(deltaTime) == false) then
        table.remove(players, k)
    end
end

I have also tried another loop from a given answer (https://stackoverflow.com/a/12397571/1405318), same error.

local i=0
while i <= #players do
    local player = players[i]
    if (player.update(deltaTime) == false) then
        table.remove(players, i)
    else
        i = i + 1
    end
end

Upvotes: 2

Views: 3112

Answers (1)

Chris
Chris

Reputation: 4372

Thanks to a comment (which is now deleted), I could fix it. Lua indexes starts at 1. So I just had to fix my setup to this:

-- setup players
players = {}
for i=0, 3 do
    local gp = InputHandler:gamepad(i)
    if(gp:isConnected()) then
        logMessage(i .. " is connected")
        players[i+1] = createCharacter(i, gp)
    end
end

Upvotes: 3

Related Questions