2

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
Community
  • 1
  • 1
Chris
  • 4,255
  • 7
  • 42
  • 83

1 Answers1

3

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
Chris
  • 4,255
  • 7
  • 42
  • 83
  • 1
    How does this solve the remove problem? `table.remove` is not safe in a loop. You can't do that. It moves other entries in the table around. And that screws up `pairs` and manually counted loops. – Etan Reisner Jan 08 '16 at 15:00
  • By using the second while loop, which controlls the loop variable manually? – Chris Jan 08 '16 at 16:40
  • Oh true, your manual loop looks like it accounts for the removal. And yes, starting at 1 would give you an off-by-one issue. I see how this fixes it in the `while` loop case now. (I'd have used `for i=1,4` instead probably but .) – Etan Reisner Jan 08 '16 at 17:22