2 Replies Latest reply on May 30, 2006 5:06 PM by Newsgroup_User

    Passing variables: Functions

    Tolk Level 1
      Sorry if this is nooby questions:
      How can i pass variables between functions in AS. I know how to return a value and you can pass parameters into a function but say I had an outer function (say "a") with a local var (say "vara") with a subtended function (say "b") how can i pass "vara" into function b and then return it out so the value of "vara" has been updated. Sorry if bad explanation. Is this possible with local vars? or would i have to use a regular var which both functions can access?
        • 1. Re: Passing variables: Functions
          TimSymons Level 1
          No sure if this is what you are looking for but it may suit your needs.

          function a():Void {

          var vara:Number; // or whatever type you need

          vara = b(vara);
          }

          function b(v:Number):Number {
          v = v + 10;
          return v;
          }

          This will basically do what your asking. If I missed the mark let me know.

          Tim
          • 2. Re: Passing variables: Functions
            Level 7
            > This will basically do what your asking. If I missed the mark let me know.

            I think you did

            >> say I had an outer function
            >> (say "a") with a local var (say "vara") with a subtended function (say
            >> "b") how
            >> can i pass "vara" into function b and then return it out so the value of
            >> "vara"
            >> has been updated.

            Short answer .. no .. you can only pass things by value, and you can only
            return values.

            You cannot pass a variable into a function and have the function modify the
            variable.

            If you want to update a single variable with the result of a function, then
            you can do as TimSymons suggested: vara = b(vara);

            But that doesn't seem to be what you're asking.

            You can, however, put your variables inside an Object, pass the Object to a
            function, and modify the variables inside the object, then when the function
            returns, the object has the modified variables. eg

            function a() {
            var myvars = { vara : 123, varb : 456};
            b(myvars);
            trace(myvars.vara);
            trace(myvars.varb);
            }

            function b(myvars) {
            myvars.vara = myvars.vara * 2;
            myvars.varb = 789;
            }
            --
            Jeckyl