Page 1 of 1

Removing Tables ... [RESOLVED]

Posted: Tue Jul 16, 2013 4:22 am
by WolfNinja2
Hey guys, it's been a while!

I haven't programmed in a while and am already running into an error ... here is the code that isn't working.

Code: Select all

for i,v in ipairs(bullet) do
	v.y = v.y + (bullet_speed * dt)
	if v.y > w/2 then
		table.remove(v)
	end
end
table.remove(v) isn't removing bullets. I am obviously being newby and terrible but I can't find anything to help online |:

Re: Removing Tables ...

Posted: Tue Jul 16, 2013 4:41 am
by substitute541
Your first problem is that the arguments for table.remove are table and the index (table.remove(table, index))

And even if you correct that, you will encounter the second problem when removing a bullet.

Here's what will happen if you do it the ordinary way

Code: Select all

Let's say a table has 5 bullets. Here's what will happen if you remove all bullets.
1. Remove the first one (at this stage, i=1)
2. Loop through, increasing index by 1 (i=2)
3. This is where it will error: Remove the 2nd one.
Why the 3rd line wont work is because all the other elements get pushed back by one index, so removing the 2nd one will actually remove the 3rd one.

A way to fix this is to loop backwards.

Here's the fixed version:

Code: Select all

for i=#bullet, 1, -1 do
   local v=bullet[i]
   v.y = v.y + (bullet_speed * dt)
   if v.y > w/2 then
      table.remove(bullet, i)
   end
end

Re: Removing Tables ...

Posted: Tue Jul 16, 2013 12:50 pm
by Plu
Just to point it out more clearly: you put the index as the second argument to table.remove, not the value. It's correct in substitute's example.

Re: Removing Tables ... [RESOLVED]

Posted: Sun Dec 27, 2015 12:41 am
by eduwhan
thank you substitute541
You saved me a lot of headache. Could not understand why removing values from table was giving unexpected result.
Read you post, and now iterated the table in reverse and then removing values. All problems solved. You're a life saver.