所以我试图从数组中删除一个元素,但最终总是出现异常:
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
多亏了一条注释(现已删除),我可以修复它。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