Clearing/resetting variables for generic functions

So I've found myself at an impasse, and I think it's due to my lack of knowledge specific to javascript. I have a function that performs a calculation. It returns the total value to a Field. The problem is that it holds on to the variables used, and I can't find a way to reset them. I'm trying to use this function on several fields with different names, but the variables get linked for both. Is there a way to have variables reset to a default value after a function is run? I tried resetting them right before the return, and then run an if statement at the beginning to catch the rest, but it causes issues. Namely, I think it starts the entire function over or something strange, resulting an incorrect returned value. This would work in C++, I believe, but JS is just different enough to make me question what I feel should be correct.
function KARMA_COST(Cost,Rank)
{
   if(Pos == 1)
   {
      Total = 0;
      Mod = 1;
   }

   if((Rank > 0) && (Pos <= Rank))
   {
      Total = (Cost * Pos) + Total;
      Pos = Pos + 1;
   }

   if((Pos == Rank+1) && (Race.Text == "Bhargastian"))
   {
      Mod = 0.50;
      Total = Total * Mod + Total;
      Pos = Pos + 1;
   }

   Pos = 1;
   return Total;
}

Comments

  • Declare (and initialize) your variables. That code, as written, would work in neither Java nor C.

    See http://java.about.com/od/understandingdatatypes/a/declaringvars.htm for some basic discussion.

    Edit: Also, Chaacter Sheet Designer's help file documents a really, really odd if function -- one that seems specifically designed to preclude that sort of logical flow.
  • Yes, declare the javascript variables first with "var", like "var Total". Otherwise you are creating global variables that can be accessed elsewhere in the script.

    Also, remember in the JavaScript code, you need to reference the fields like

    Edit1.Text
    or
    Edit1.Value (for strictly numeric values)

    and not just Edit1 as you would in non-javascript functions.

Leave a Comment