Remove and add to array

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
feelixe
Prole
Posts: 36
Joined: Tue Aug 20, 2013 10:29 am

Remove and add to array

Post by feelixe »

Hey, in my game i have an array with the enemies, like this:

Code: Select all

	Enemies = { }
	Enemies.Enemy = { }
I add enemies to the array with the following code:

Code: Select all

	cE = #Enemies.Enemy + 1
	Enemies.Enemy[cE] = { }
	Enemies.Enemy[cE].X = posx
	Enemies.Enemy[cE].Y = posy
	Enemies.Enemy[cE].type = tt
	Enemies.Enemy[cE].actX = posx
	Enemies.Enemy[cE].actY = posy
	Enemies.Enemy[cE].HP = 5
	Enemies.Enemy[cE].Alive = true
	Enemies.Enemy[cE].attacking = false
	Enemies.Enemy[cE].current_State = "r"
	Enemies.Enemy[cE].damaged = "s"
	Enemies.Enemy[cE].direction = playerQuad.down
	entities_map[posy/50][posx/50] = 20
	print(time.."s :Enemy spawned @ "..posx..", "..posy.." #"..#Enemies.Enemy+1)
And when they are killed i use this code(simplified):

Code: Select all

for b=1, #Enemies.Enemy do
	if bx == Enemies.Enemy[b].X and by == Enemies.Enemy[b].Y and Enemies.Enemy[b].Alive == true then
		if Enemies.Enemy[b].HP <= 0 then
			table.remove(Enemies.Enemy, b)
		end
	end
end
But when every there are more then/or two enemies in the array and one is killed the game crashes and says there's an error the second line in the last code segment, saying it tried to index a nil value, I understand the error message but i just can't seem to figure out what's wrong, any help would be appreciated, thanks:)
User avatar
DaedalusYoung
Party member
Posts: 413
Joined: Sun Jul 14, 2013 8:04 pm

Re: Remove and add to array

Post by DaedalusYoung »

table.remove shifts all the next entries back, so your for-loop will eventually hit a value that does not exist anymore.

To fix this, iterate backwards:

Code: Select all

for b = #Enemies.Enemy, 1, -1 do
    if Enemies.Enemy[b].HP <= 0 then
        table.remove(Enemies.Enemy, b)
    end
end
Post Reply

Who is online

Users browsing this forum: Ahrefs [Bot], Bing [Bot], YaCy [Bot] and 2 guests