An excerpt from an answer to a similar question...
Parameters and local variables are allocated on the stack (with reference types the object lives on the heap and a variable references that object). The stack typically lives at the upper end of your address space and as it is used up it heads towards the bottom of the address space (ie towards zero).
Your process also has a heap, which lives at the bottom end of your process. As you allocate memory this heap can grow towards the upper end of your address space. As you can see, there is the potential for the heap to "collide" with the stack (a bit like techtonic plates!!!).
A Stack Overflow error means that the stack (your subroutine) overflowed (executed itself so many times that it crashed). Stack Overflow errors usually result from a bad recursive call (in the case of AppleScript, a bad subroutine call).
In general, if your subroutines return values, make sure that value is not the subroutine name. Otherwise the stack will overflow, crashing your program (if the return statement is not inside a try
block). Just change this:
return calculate_result(this_result)
...to this
return this_result
...and you should be good to go!
In some cases it is fine to return the subroutine name, but only if there is a terminating condition. For example, if a user entered an invalid number, the subroutine could rerun itself, but only if the number was invalid (shown below):
on get_input()
set this_number to null
try
set this_number to the text returned of (display dialog "Please enter a number:" default answer "") as number
on error --the user didn't enter a number and the program tried to coerce the result into a number and threw an error, so the program branches here
return get_input()
end try
return this_number
end get_input
In the above case, the terminating condition occurs when a user enters an actual number. You can usually tell when a program will throw a Stack Overflow error because there is no terminating condition.
I hope this information helps!