View Single Post
  #2  
Unread 05-21-2012, 05:29 AM
D.H1cks's Avatar
D.H1cks D.H1cks is offline
The Undying
Interface Author - Click to view interfaces
 
Join Date: Apr 2007
Posts: 162
An interesting question, and now I know the answer myself. I suggest that whenever you have questions about how LUA operates, set up an experiment and you can discover things. For example, for your problem I wrote the following in a dummy plugin:

Code:
     self.testTable = { "apple", "oranges", "cherries", "bananas", "tomato", "strawberries", "blueberries", "pears", "blackberries" }

	for i, item in ipairs(self.testTable) do
		Turbine.Shell.WriteLine(i .. ": " .. item);
	end

	Turbine.Shell.WriteLine("Delete Item");

	for i, item in ipairs(self.testTable) do
		if(item == "tomato" or item == "strawberries" ) then
			table.remove(self.testTable, i);
		end
	end

	Turbine.Shell.WriteLine("Next loop");

	for i, item in ipairs(self.testTable) do
		Turbine.Shell.WriteLine(i .. ": " .. item);
	end
The code basically will attemp to remove 2 items from the table that are next to each other, here was the output:

Code:
### Chat Log: General 05/21 06:06 AM ###
1: apple
2: oranges
3: cherries
4: bananas
5: tomato
6: strawberries
7: blueberries
8: pears
9: blackberries
Delete Item
Next loop
1: apple
2: oranges
3: cherries
4: bananas
5: strawberries
6: blueberries
7: pears
8: blackberries
Loaded plugin "tester".
As you can see, the second item did not get deleted.

Also, I tried to remove both "tomato" and "blueberries", which worked exactly as expected. So basically, removing a single item from a table while iterating with ipairs means you cannot access the item immediately following the item you delete.

I think your best bet is to do your reverse iteration:

Code:
for i = table.getn(tablename), 1, -1 do
   local item = tablename[i];

   -- search and remove code
end
Reply With Quote