A loop needs to execute until a certain condition is met.
ColdFusion offers several different ways to operate a loop. Loops for queries, indexes, arrays, collections and conditional. To solve the problem of looping until a certain condition is met, a conditional loop will be used.
There are several instances where an application will want to loop until a certain condition is met. For example a craps game will want to continue to roll dice until the roll of the dice is 7 or the point is made. This is done quite easily with a conditional loop.
This code assumes the code to establish the point and thus the point is hardcoded.
<cfset point = 4 /> <cfoutput> The point is #point#! Good luck!<br/><br/> </cfoutput>
The next thing that needs to be done is to establish the first roll. This is done using the RandRange() function and giving it the range of possible dice roles, two to twelve.
<!--- roll the dice, so to speak ---> <cfset roll = RandRange( 2,12,"SHA1PRNG" ) />
Once the roll has been established the conditional loop starts, in this case the loop executes as long as the roll is not 7 or 4.
<!--- as long at the point is not made and we don't crap out, role again! ---> <cfloop condition="roll NEQ 7 AND roll NEQ #point#"> <!--- roll the dice again ---> <cfoutput> #roll#<br/> </cfoutput> <cfset roll = RandRange( 2,12,"SHA1PRNG" ) /> </cfloop>
Once the loop has finished executing determine whether the player passed or crapped out.
<cfif roll EQ point> You Pass! <cfelse> You Crapped Out! </cfif>
Running the above code will produce a variation of the following:
There are many uses for conditional loops in applications and ColdFusion once again makes it simple!
+