A "while" loop...deleting an item in that while loop count...**SOLVED**

Started by Knox, Tue 01/03/2011 19:22:56

Previous topic - Next topic

Knox

Hi,

Im running into a problem mostly due to my newbie-ness: Ive got a while loop using the number of inventory items in a certain "myInventoryWindow" window. Inside this loop, I run a script that does stuff + and eventually decides (depending on various factors) if that item "i" should be deleted from myInventoryWindow.

The problem is, if I delete an item in that window from inside the while loop, how in the crap am I supposed to update "iMyItemCount" so that it diminishes its amount?

Im guessing I have to use a dynamic array?

Code: ags

//Pseudo code:

  iMyItemCount = myInventoryWindow.ItemCount;
  int i = 0;
  while (i < iMyItemCount) 
  {
        functionThatDeletesItemFromInvWindow(); //processes 1 item at a time, to see if it must be deleted
        i++;
  } 
--All that is necessary for evil to triumph is for good men to do nothing.

Khris

Hmm, I'd say this should do:

Code: ags
  if (item was deleted) iMyItemCount--;
  else i++;


The while condition is checked every loop, that's the whole point of "while". So if you've just removed InvWindow.ItemAtIndex[i], simply decrease iMyItemCount by one and don't increase i since the deletion moves the next item to the current i and the end one down.

Knox

oh wow, I did not know we could do that! Geeze, I was afraid I'd have to use global vars, dynamic arrays, etc...shows how noob I am! :P

You just saved me a crapload of work man...
--All that is necessary for evil to triumph is for good men to do nothing.

Calin Leafshade

the best way to do this is to make your functionThatDeletesItemFromInvWindow(i) function return true or false depending on whether or not an item was deleted. That's nice and neat

SMF spam blocked by CleanTalk