Recursive functions...

Started by monkey0506, Tue 07/06/2005 18:03:10

Previous topic - Next topic

monkey0506

Just wondering, are recursive functions implemented?  I can't seem to find documentation on them, yet they seem to compile.  However, they also don't appear to be working correctly:

Code: ags
/* global script */

function doStuff(short doWhat) {
  if (doWhat == 1) return AGS_MAX_GUIS * 3 * AGS_MAX_CHARACTERS;
  else if (doWhat == 2) {
    short prevWhat = doStuff(1);
    return prevWhat * doWhat;
    }
  else {
    return -1;
    }
  }

/* game_start */
  Display("%d ## %d ## %d", doStuff(1), doStuff(2), doStuff(3));
  Display("%d ## %d ## %d", AGS_MAX_GUIS * 3 * AGS_MAX_CHARACTERS, AGS_MAX_GUIS * 3 * AGS_MAX_CHARACTERS * 2, -1);


The problem is well, like I said, it compiles, but it doesn't work.  The values displayed are:

"45000 ## -41072 ## -1"

And

"45000 ## 90000 ## -1"

As you can see, they aren't the same, though they should be.  When the call "doStuff(1)" is made from within the function doStuff(short doWhat), it appears to be return some junk value.  Is this because recursive function's aren't implemented (if so, why do they compile?); or is it something I've done wrong (if so, what?)?

Thnaks for any help.

Pumaman

You're using a "short" variable, but shorts can only store numbers up to 32767 before they wrap round.

Please, always use an "int" for variables unless you're creating a huge array and need to be very memory conscious.

monkey0506

Oh... Heh.  I thought it could get bigger than that.  Silly me.  Most of the variables I've been using lately don't get bigger than 100, so that's why I've been using shorts a lot lately.  And actually, changing the parameter to "int" didn't change anything.  I've tested it several times, and I'm still getting the same results.  Oops... Nevermind.  I forgot to change the local variable as well as the parameter.  It works now.

Nice to know that recursive functions are implemented BTW.

Pumaman

I'd just like to clarify that there is no point in using a short rather than an int as a local variable. In fact, ints are faster because the CPU is better at reading/writing 32-bit chunks of memory than it is at 16-bit chunks.

So please people, use an int unless you have a very good reason not to ;)

Rui 'Trovatore' Pires

Oh. Then why do shorts exist at all? Anyway, what about chars? I use them a lot. Should I not?
Reach for the moon. Even if you miss, you'll land among the stars.

Kneel. Now.

Never throw chicken at a Leprechaun.

Pumaman

If you're using chars to store or manipulate a character, then fine.

But I wouldn't use a char just to represent a number. shorts exist because there are some situations where you want a large array and using an int would consume too much memory. But for everyday variables, just use an int.

monkey0506


SMF spam blocked by CleanTalk