The loop
function also passes the return value of each recursive pass back to the loop function, though this is not
90
Part I: The Core Language
as evident in this particular example. To see this in action, it is better to provide code to track the
recursion before and after the recursive function call:
public static function main()
{
var i = 0;
i = loop( i );
trace( i ); // Outputs: 0
}
public static function loop( num : Int ) : Int
{
var ret = 0;
return if ( num < 6 )
{
trace( num );
ret = loop( num + 1 );
trace( ret );
--ret;
} else num;
}
In this example, the value first passed to the loop function is incremented with each call to the loop
function during the recursion. As the recursive calls are made in the middle of the loop function, the
execution of each call ends at that point while the new call is being made. Eventually, the incrementing
value reaches the value 6, so the loop function is no longer recursively called, and instead, the last
passed value is returned. This then has a knock on effect for each of the parent loop calls, which in turn
decrement the value before passing it back.
Pages:
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210