do-while loop syntax

Hi,

I just needed to use a do-while loop and couldn’t get it to compile without errors, there’s a cryptic message (which doesn’t mean anything to me) about a missing semicolon where there’s nothing missing IMO.

Here’s the code:

do {
		var spawnIndex : int = Mathf.RoundToInt(Random.value * SpawnPointCount);
		transform.position = SpawnPoints[spawnIndex].transform.position;
	} while (true);

IMO this should work just fine, also according to the JavaScript resources which get mentioned in the forums and the wiki.
Thanks in advance!!!
Regards

What about…

while (true)  { 
      var spawnIndex : int = Mathf.RoundToInt(Random.value * SpawnPointCount); 
      transform.position = SpawnPoints[spawnIndex].transform.position; 
}

Although, I am not sure how you are supposed to exit from this.

You should also put a yield in there so you can interrupt this with the PAUSE button if it gets into an endless loop (which it currently is), so…

while (true)  { 
      var spawnIndex : int = Mathf.RoundToInt(Random.value * SpawnPointCount); 
      transform.position = SpawnPoints[spawnIndex].transform.position;
      yield;
}

the do … while construct is not supported by the current version of Unity JavaScript. You can emulate it using a while loop, though:

Replace

do {
    ...
} while ( xx );

with

while (true) {
    ...
    if ( ! xx ) break;
}

I think you can just use the “for” construct with no conditions if you want an endless loop:-

for (;;) {
    /* Something useful here */
}

Slightly less typing than “while (true)” and a more explicit idiom.

That’s basically a matter of preference since both will probably compile down to the same byte codes. I prefer while(true) as I think it’s more explicit than for( ;; ) which to me more resembles line noise coming from an old 900 baud modem than actual code :slight_smile:

And that’s coming from me who actually used to enjoy writing advanced regular expressions in perl! :wink:

Now if only we could get goto’s!

This is a fun spec:

http://projectfortress.sun.com/Projects/Community/browser/trunk/Specification/fortress.1.0.pdf

discussion of loops by Steele and Hejlsberg:

Eh yeah, I prefer while(true) as well because for me, any “for” is designed for some counting, and any “foreach” is designed for iterating through a collection. Only “while” is designed for me to have a custom break requirement.

lol gotos. Very niche reason for using them, but I can only imagine if they were implemented in Unity they would be abused like nobody’s business.