PDA

View Full Version : Problem with Programatic Recursion in UDF



Blypht
07-15-2004, 03:41 PM
I'm trying to implement a recursive function in LScript and am having a problem. It works fine going in (all the arguments work as they should). However, the return value is not working as I would expect.

Here is the code:

@version 2.2
@warnings
@script generic
@name "Recursion Test"

generic
{
Done = Recurse(5);
info("Done = ",Done);
}

Recurse: Count
{
info("Count = ",Count);

// Force Result to be a number type
Result = 0;

// Escape from recursion if Count == 0
if (Count > 0)
{
Result = Recurse(Count - 1);
Result++;
info("Result = ",Result);
}

return(Result);
}

I would expect that the info messages would go as follows:
Count = 5
Count = 4
Count = 3
Count = 2
Count = 1
Count = 0
Result = 1
Result = 2
Result = 3
Result = 4
Result = 5
Done = 5

Instead, I get:
Count = 5
Count = 4
Count = 3
Count = 2
Count = 1
Count = 0
Result = 1
Result = 1
Result = 1
Result = 1
Result = 1
Done = 1

Any help would be appreciated.

Thanks!

#lwrs_web
07-15-2004, 04:56 PM
confirmed...
BUG in LScript

Lito
07-15-2004, 05:27 PM
Not a bug. The problem is that your always reinitializing the Result Variable to 0 when you call recurse.

Result = 0 should not be in the function Recurse.

If you make Recurse a global variable it should work as you expect.

#lwrs_web
07-15-2004, 05:34 PM
then maybe my C compiler is buggy?

;)



int Recurse(int Count)
{
int Result = 0;
printf("Count = %d\n", Count);
if(Count > 0)
{
Result = Recurse(Count - 1);
Result++;
printf("Result = %d\n", Result);
}
return(Result);
}

int main(int argc, char* argv[])
{
printf("Recurse: %d\n", Recurse(5));
}

Count = 5
Count = 4
Count = 3
Count = 2
Count = 1
Count = 0
Result = 1
Result = 2
Result = 3
Result = 4
Result = 5
Recurse: 5

Lito
07-15-2004, 06:00 PM
oops my bad. Shouldn't read so fast when looking a recusion ;)