Removing Tables ... [RESOLVED]

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
User avatar
WolfNinja2
Party member
Posts: 150
Joined: Wed Oct 24, 2012 10:10 pm

Removing Tables ... [RESOLVED]

Post 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 |:
Last edited by WolfNinja2 on Tue Jul 16, 2013 5:30 pm, edited 1 time in total.
User avatar
substitute541
Party member
Posts: 484
Joined: Fri Aug 24, 2012 9:04 am
Location: Southern Leyte, Visayas, Philippines
Contact:

Re: Removing Tables ...

Post 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
Currently designing themes for WordPress.

Sometimes lurks around the forum.
User avatar
Plu
Inner party member
Posts: 722
Joined: Fri Mar 15, 2013 9:36 pm

Re: Removing Tables ...

Post 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.
User avatar
eduwhan
Prole
Posts: 3
Joined: Sun Jan 11, 2015 10:21 pm

Re: Removing Tables ... [RESOLVED]

Post 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.
Post Reply

Who is online

Users browsing this forum: Ahrefs [Bot], Google [Bot] and 48 guests