Removing items from table doesn't work

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
fkinCURRY
Prole
Posts: 4
Joined: Thu Nov 29, 2018 12:31 pm

Removing items from table doesn't work

Post by fkinCURRY »

When the code runs, the cubes aren't disappearing after their ttl is larger than 100 (if it even counts)

Code: Select all

for i,v in ipairs(cubes.cube) do	
	if v.y < height - 20 then
		v.y = v.y + cubes.speed
	else
		if v.ttl > ttlg then
			table.remove(cubes.cube, i)
		end
	end
	v.ttl = v.ttl + 1	
end
When I moved the table.reomve() outside the if it did remove them but right after hitting the bottom.
I added the ttl variable so that they can stay there for a while (ttlg = 100) and when ttl > ttlg then it would remove it but it doesn't.
Tought that table.remove() might be the problem as people don't like this solution so i used cubes.cube = nil but that removed all of them.

The problem could also be in something else I'm just a beginner in both Lua and LÖVE.

(They were pictures of cubes before but replaced them with snowflakes since x-mas is getting closer)

Thanks for help in advance.
Attachments
cubes.zip
(29.56 KiB) Downloaded 131 times
Astorek86
Prole
Posts: 20
Joined: Fri Jul 13, 2018 7:35 pm

Re: Removing items from table doesn't work

Post by Astorek86 »

I downloaded your Attachment. To be honest, I couldn't see any Problem with "table.remove". For me (LOVE 11.2, 32bit), it works perfectly.

I replaced the Line where you print "Total" with...

Code: Select all

love.graphics.print("Total: " .. #cubes.cube, 1, height - 15)
... and it works, as far as I can tell^^... Snow is falling to the bottom, stays for a while and then it disappears...
User avatar
ivan
Party member
Posts: 1911
Joined: Fri Mar 07, 2008 1:39 pm
Contact:

Re: Removing items from table doesn't work

Post by ivan »

If you want to remove elements during iteration, you have to iterate in reverse:

Code: Select all

for i=#cubes.cube, 1, -1 do
  local v = cubes.cube[i]
Otherwise you get "gaps" in the table.
fkinCURRY
Prole
Posts: 4
Joined: Thu Nov 29, 2018 12:31 pm

Re: Removing items from table doesn't work

Post by fkinCURRY »

Many thanks for the replies. It seems to be working properly now.
Post Reply

Who is online

Users browsing this forum: No registered users and 46 guests