Page 1 of 1
Table remove
Posted: Thu Feb 21, 2013 3:00 am
by tdc5013
Hi,
I'm trying to compare all entries of a table against all entries of another, any identical entries then being removed from the second table. The problem is a for loop will only let me check whatever entries the iterator happens to correspond to at that moment. I'm looking to compare every single entry of both tables against one another.
Apologies if this is really simple, but it's way past my bedtime and this has me stumped.
Thanks in advance!
Re: Table remove
Posted: Thu Feb 21, 2013 3:27 am
by substitute541
What about a double for-loop?
Code: Select all
for i=1, #table1 do
partA = table1[i]
for j=1, #table2 do
partB = table2[j]
if partA == partB then table.remove(table2, j) end
end
end
If someone haven't noticed, that's almost the same as my collision-detection loop, minus the optimization since both tables might not have the same number of indices.
Re: Table remove
Posted: Thu Feb 21, 2013 3:40 am
by tdc5013
Thanks for the quick reply.
Just to make sure I understand I'll get more specific as to what my problem is:
I have two tables filled with objects that may or may not have the same index value at any given time. The objects are cards with a suit and number attribute.
The check will be if the Suit and Number of the entry in the first table is identical to that of the second then remove said entry from the second table.
Code: Select all
for i = 1, #table1 do
for j = 1, #table2 do
if( table1[i].n == table[j].n and table1[i].s == table2[j].s ) then
table.remove(table2, j)
end
end
end
Will this code do the trick?
Thanks again for the help.
Re: Table remove
Posted: Thu Feb 21, 2013 3:44 am
by Taehl
Since you're removing things, I highly recommend iterating backwards so that table.remove won't mess you up. Like so:
Code: Select all
for i=#table1, 1, -1 do
for j=#table2, 1, -1 do -- backwards!
if( table1[i].n == table[j].n and table1[i].s == table2[j].s ) then
table.remove(table2, j)
end
end
end
Otherwise you may end up skipping entries, and getting other subtly wrong behavior.
Re: Table remove
Posted: Thu Feb 21, 2013 3:54 am
by tdc5013
That's great advice, thank you.
While I'm on the subject of for loops I may as well ask: If I return a table entry 'i' during a for loop will that automatically end the loop? Or will it keep on looping and returning until it's defined stopping point?
Re: Table remove
Posted: Thu Feb 21, 2013 4:02 am
by Taehl
Using a "return" will take you out of whatever function you're in. If you want to exit just the innermost loop, you can use "break". For further reading, check out
http://www.lua.org/manual/5.1/manual.html#2.4.4.
Re: Table remove
Posted: Thu Feb 21, 2013 4:11 am
by tdc5013
I'll take a look.
Thanks for your help, it was really useful!