2011-08-12 71 views
0

我刚开始使用applescript,并听说过子程序。所以我决定编写一个测试程序,它将一个数字加起来,将它增加9,减去27,除以3,然后返回结果。只有它不返回结果;它将返回一个StackOverFlow错误。什么是StackOverFlow错误?AppleScript - StackOverflow错误

程序编译正确,我不知道什么是错的。就像我说的,我是非常适合新的applescript。下面是我运行代码:

calculate_result(text returned of (display dialog "Enter a number:" default answer "")) 

on calculate_result(this_result) 
    set this_result to this_result + 9 
    set this_result to this_result - 27 
    set this_result to this_result/3 
    return calculate_result(this_result) 
end calculate_result 

回答

2
return calculate_result(this_result) 

您递归调用再次通过this_result给它的子程序,进而被调用的函数调用子程序等。变量,函数返回地址等驻留在堆栈上。由于子例程的递归性质,堆栈溢出。

2

在“calculate_result”中,最后一行再次调用“calculate_result”。行更改为:

return (this_result)

子程序中的最后一行是刚刚再次调用子程序,从而再次调用子程序,从而再次调用子程序,从而再次调用子程序,从而再次调用子程序...

我认为你的想法 - 你写的AppleScript - 崩溃,因为它只是不断调用自己,并最终耗尽内存,从而触发堆栈溢出错误。

任何时候程序用尽某种内存空间时都会发生堆栈溢出错误 - 它不是特定于AppleScript--它可能发生在任何编程语言中。看到这个答案的堆栈溢出错误的更深入的解释是:

What is a stack overflow?

3

an answer to a similar question摘录...

参数和局部变量是在栈上分配(使用引用类型,对象位于堆上,变量引用该对象)。堆栈通常位于地址空间的上端,当它用完时它将朝向地址空间的底部(即趋近于零)。

您的进程还有一个堆,它位于进程的最后端。当你分配内存时,这个堆可以向你的地址空间的上端增长。正如你所看到的,堆有可能与栈“碰撞”(有点像techdonic板!!!)。

堆栈溢出错误意味着堆栈(你的子程序)溢出(执行本身很多次,它崩溃了)。堆栈溢出错误通常是由不良的递归调用引起的(对于AppleScript,子例程调用不正确)。

通常,如果您的子例程返回值,请确保该值不是子例程的名称。否则,堆栈将溢出,导致程序崩溃(如果return语句不在try块内)。只是改变这一点:

return calculate_result(this_result) 

...到这

return this_result 

...你应该很好去!

在某些情况下,可以返回子程序名称,但只有在存在终止条件时才可以。例如,如果一个用户输入了一个无效的数字,此子程序可以重新运行本身,而是仅如果数为无效的(如下所示):

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 

在上述情况下,发生终止条件时,用户输入一个实际的号码。您通常可以知道程序何时会抛出堆栈溢出错误,因为没有终止条件。

我希望这些信息对您有所帮助!

+0

不公平...有人高举我然后把它拿走:( – fireshadow52

+0

+1来平衡:) – Mahesh

+0

+1的所有答案;他们都很好:) – fireshadow52