Recursive Subroutines
A recursive subroutine is a subroutine that calls itself. Recursive subroutines are legal in AppleScript. You can use them to perform repetitive actions. For example, this recursive subroutine generates a factorial.
on factorial(x) if x > 0 then return x * (factorial(x - 1)) else return 1 end if end factorial factorial(10)To generate 10 factorial, the subroutinefactorialis called once from the
top level of the script, and then calls itself ten more times, until the value ofxis 0. Whenxis equal to 0, AppleScript skips to the Else clause and finishes executing all the partially executed subroutines, including the originalfactorialsubroutine call.When you call a recursive subroutine, AppleScript keeps track of the variables and pending statements in the original (partially executed) subroutine until the recursive subroutine has completed. The limit on the number of pending subroutines depends on the amount of memory available.