View Single Post
  #1  
Unread 05-20-2012, 09:23 PM
Niwashi's Avatar
Niwashi Niwashi is offline
The Undefeated
Interface Author - Click to view interfaces
 
Join Date: Feb 2011
Posts: 7
How does ipairs handle deletes from a table?

I want to have something like the following in my script:

Code:
	-- remove items from currencyList that are no longer in the wallet
	for i, currencyItem in ipairs(currencyList) do
	
		-- check if this is still in the wallet
		local walletItem = GetWalletItemByName(currencyItem.Name);
	
		if walletItem == nil then -- item no longer in wallet, so remove from list
		
			table.remove(currencyList, i);
			ChangesMade = true;
			
		end

	end
but I'm not sure how the table.remove will impact cycling through items in the table. In C++, I'd deal with that by iterating backwards through the table, from the last item to the first one, so that removals don't move the items I still have to search through. In LUA, I could iterate backwards with a for loop using the pattern "for i = 10, 1, -1 do", but using the form "for k, v in ipairs(t) do" there doesn't seem to be a step parameter to specify that I want to search backwards. Will the code above hit every item in the table, even if the indexes change from a call to table.remove? Or if not, then how do I search through a table to find items that need to be removed?

(Sorry if this is an elementary question, but I'm still learning the LUA scripting language, and the online tutorial on it that I found didn't cover this question.)
Reply With Quote