• Hey Guest! Ever feel like entering a Game Jam, but the time limit is always too much pressure? We get it... You lead a hectic life and dedicating 3 whole days to make a game just doesn't work for you! So, why not enter the GMC SLOW JAM? Take your time! Kick back and make your game over 4 months! Interested? Then just click here!

GML Extending a loop from within itself

M

mochipon

Guest
Let's say I have a piece of code like this:

Code:
list_items = 5;
loop_counter = 0;
for (var i = 0; i < list_items; i++) {
 if (condition so and so) { list_items++; }
 if (condition this and that) { list_items++; }
 loop_counter++;
}
Is the number of iterations of the for loop fixed at the time it's started (when list_items is = 5)? If I increase the value of list_items to 7 or 8 before the loop has reached its fifth iteration, will it go on to 7 or 8, if the condition was met and list_items is now higher than when the loop was started? In other words, will the variable loop counter always be 5 at the end of the thing, or can it go higher?

If so, can a while loop do something else? How can I dynamically extend the number of loops based on conditions met inside the loop? I'm kind of suspecting it's fixed, but maybe I'm mistaken and there's some other error inside my code. Do I have to use something like a recursive call of a script instead?
 

Simon Gust

Member
I think this should work with increasing list_items.
Just make sure you don't create an infinite loop.

A while loop should work the same.
Code:
list_items = 5;
var i = 0;
while (i++ < list_items)
{
  if (blablabla) list_items++;
}
 
Also, as a side-note, be aware that GMS does not play well with recursion. It will allow you to recursively call something a few times (I think the limit is somewhere between 100-200 times) and then it will throw an error. So usually don't try actual recursion and use something like a stack or a queue instead if you feel the need for something to act recursively.
 
Top