Log In  

Me again, sorry.
I have a table called ENEMY that holds... well enemies.
Every thing works as want so far apart from deleting from the table.

I have two enemies at the moment.
Number 1 is a snake.
Number 2 is a spider.

Then I have this to kill them off:

  for en=1,#enemy do
  -- this line below stops working
    if box_hit(enemy[en].x,enemy[en].y) then
      if enemy[en].mode=="patrole" then
        plyr.hit_enemy = true
        plyr.struck_by_x=enemy[en].x
      end
      if enemy[en].mode=="dead" then
        plyr.hit_enemy = false
      end
      if enemy[en].mode=="pickup" then
        plyr.hit_enemy = false
        score+=enemy[en].score
        del(enemy,enemy[en])
      end
    end
  end

If I kill the spider first, it works.
If I kill the sname first it throws an error attempt to index field '?' a nil value.

I put it down to the DEL line at the end.
Does it look correct or is there more to deleting from a table than I know of?

Many thanks
Peej

P#96363 2021-08-22 22:13

1

If you're deleting from the table, you should do the loop from the end instead of the beginning:

for en=#enemy,1,-1 do

That should prevent your error. What happens is that #enemy is evaluated when you construct the loop, so if you have 2 things in the enemy table, #enemy evaluates to 2 when the for statement is run. Then when you delete something, there's now only one enemy in the table. If the enemy you deleted is at the end of the table, you're fine because that would be the last iteration of the loop. If not, then eventually your code tries to get enemy[2], which no longer exists due to the previous deletion, and that's where your error comes from.

If you go backwards, you're starting at enemy[2] which will definitely exist at the start of your loop. If you delete something, you're still down to 1 thing in your enemy table, but now the next number in the loop is 1 instead of 2 because you're going backwards, so you won't get an error.

Does that make sense?

P#96366 2021-08-22 23:16
:: Peej

I knew it had to be something like that!
Thanks so much @2bitchuck my enemies now delete perfectly.
Cheers

P#96392 2021-08-23 18:34

One other minor thought: Consider using deli() instead of del(), since you already have the index of the item you're deleting so there's no need to search the table for the enemy. It won't make a difference when the enemy table is only 2 entries long, but if/when it gets longer, it might. (Plus, it'll save a couple tokens to use deli(enemy,en) instead of del(enemy,enemy[en]))

P#96394 2021-08-23 19:14 ( Edited 2021-08-23 19:16)
:: Peej

Oh, that is nice.
Thanks for the tip, @TBMcQueen. Much appreciated.

P#96396 2021-08-23 19:27

[Please log in to post a comment]

Follow Lexaloffle:        
Generated 2021-11-27 14:24:40 | 0.041s | Q:17