所以我试图从我的数组中删除一个元素,但我总是以异常结束:
bad argument #1 to 'remove' (position out of bounds)
以下是代码:
-- 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
我还尝试了给定答案(https://stackoverflow.com/a/12397571/1405318)的另一个循环,同样的错误。
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
答案 0 :(得分:2)
感谢评论(现已删除),我可以修复它。 Lua索引从1开始。 所以我只需要修改我的设置:
-- 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