Page 1 of 1

Problem with finding stuff in a table

Posted: Sat Mar 31, 2012 2:05 pm
by rokit boy
Ok so let's say I have a table called lol and I want it to delete EVERY SINGLE INSTANCE of value
I figured out this mechanism:

Code: Select all

for i = 1, #lol, 1 do
	if lol[i] == value then
		table.remove(lol,i)
		print(i)
	end
end
I did this in Java before by doing this:

Code: Select all

for (String thing : a) {
    if (thing.equals(b)) {
    print("Found it!");
    }
}
Oh god for loops are so beautiful in Java :D

To the point:
Can somebody improve my first code so it deletes EVERYTHING with the contents of "value".

A plus tard,

rokit boy (I'm not French, but I like French)

Re: Problem with finding stuff in a table

Posted: Sat Mar 31, 2012 2:38 pm
by lizard
Do not use table.remove() with large tables if you have a large amount of elements to removal. Copy elements which should not to be removed into new table, and then remove old table.

Re: Problem with finding stuff in a table

Posted: Sat Mar 31, 2012 2:41 pm
by rokit boy
My table is not large.
The rest:

Code: Select all

value = "Hello"
lol = {"Hello","Hello","Hi"}
When I do my for loop, it only removes the first hello.

Re: Problem with finding stuff in a table

Posted: Sat Mar 31, 2012 2:46 pm
by tentus
You are removing an element from a table and then continuing forwards (the second element becomes the first element, but you've already comepleted that iteration in your for loop).

Think of it like pulling steps out from a staircase, while you're climbing it. The obvious fix, then, is to walk down the staircase.

Code: Select all

function removeValFromTable(value)
	for i = #sometable, 1, -1 do
		if sometable[i] == value then
			table.remove(sometable,i)
		end
	end
end

Re: Problem with finding stuff in a table

Posted: Sat Mar 31, 2012 4:04 pm
by rokit boy
tentus wrote:You are removing an element from a table and then continuing forwards (the second element becomes the first element, but you've already comepleted that iteration in your for loop).

Think of it like pulling steps out from a staircase, while you're climbing it. The obvious fix, then, is to walk down the staircase.

Code: Select all

function removeValFromTable(value)
	for i = #sometable, 1, -1 do
		if sometable[i] == value then
			table.remove(sometable,i)
		end
	end
end
THANK YOU! Used for my WIP crappy lib. Will give you credit. Publishing the lib in a moment.