Recursive calls overwrite local variables

677 views
Skip to first unread message

Martin Lanter

unread,
Sep 23, 2011, 6:21:37 PM9/23/11
to mozilla-rhino
Dear Rhino community,

I ran into a problem with Rhine when I tried implement a recursive
function. I realized, that Rhino seemingly overwrites local variables
of a function when the function calls itself (recursively). I wrote
the following Javascript example _______________ function
recurse(reset) {
if (reset) {
i = 0;
} else {
for (i=0;i<2;i++) {
print("\nbefor recursion: i = "+i);
recurse(true);
print("after recursion: i = "+i);
}
}
}

recurse(false);
________________

This script shold stop, but it ends up spinning in an endless loop
with the following output:
befor recursion: i = 1
after recursion: i = 0

befor recursion: i = 1
after recursion: i = 0
.....

The recursive call recurse(true) overwrites the local variable i to 0.
Therefore i++ will never reach 2 and thus the function never stops.

How am I supposed to deal with this? Is there a work around or do I
need to avoid recursion at all? Is this a bug in Rhino?

Kind regards
Martin

Michael Schwartz

unread,
Sep 23, 2011, 6:25:51 PM9/23/11
to mozill...@googlegroups.com
Your "i" variable is a global variable. Your recursive function is overwriting that.
Reply all
Reply to author
Forward
0 new messages