A Flash Developer Resource Site

Results 1 to 3 of 3

Thread: Switching Variables

  1. #1
    Member
    Join Date
    Jun 2009
    Posts
    44

    Switching Variables

    Hi guys,
    You guys probably think this is simple, but I would just like to know how one would go about switching 2 variables around. For example if I have
    Code:
    a = 5;  b = 3;
    Then use the switch function and get:
    Code:
    a = 3;  b = 5;
    is there any such thing?
    thanks for your time.

  2. #2
    Prid - Outing Nig 13's Avatar
    Join Date
    Jul 2006
    Location
    Norway
    Posts
    1,864
    IGNORE THIS POST, BECAUSE I JUST TRIED IT, AND IT'S NOT WORKING, LOOK AT THE NEXT POST

    I think there is one, but I can't remember. Although, why not make a custom function for that?

    Actionscript Code:
    function switch_vars(varA, varB){
        holder1 = varA;
        holder2 = varB;
        varA = holder2;
        varB = holder1;
    }

    Then, use this to switch 2 variables:

    Actionscript Code:
    switch_vars(a, b);

    I haven't tested it yet, but hopefully, it should work
    Last edited by Nig 13; 09-06-2011 at 12:11 PM.
    I am back, guys ... and finally 18 :P

    BRING BACK THE OLD DESIGN!! OR AT LEAST FIX THE AS TAGS

  3. #3
    Prid - Outing Nig 13's Avatar
    Join Date
    Jul 2006
    Location
    Norway
    Posts
    1,864
    What the above code did, was to make a function where varA and varB can be something you type yourself, like for instance, a and b variables, and then, when calling the function to execute its codes, varA and varB are replaced with the custom variables defined by you yourself. But the problem was that varA and varB, which would refer to variables a and b, didn't take the names a and b, but rather those variables' values, so when storing their values at the beginning of the function inside two other variables, their values were stored, but when switching their values, varA and varB weren't referring to a and b variables, but rather their values, and we don't have any variables named 3 or 5. So, by instead using strings for the variable names, we can refer to the actual variables, so change your function to this:

    Actionscript Code:
    function switch_vars(varA, varB){
        holder1 = _root[varA];
        holder2 = _root[varB];
        _root[varA] = holder2;
        _root[varB] = holder1;
    }

    and to use it:

    Actionscript Code:
    switch_vars("a", "b");

    always remember quotes around your variable name in the function, otherwise it won't work
    I am back, guys ... and finally 18 :P

    BRING BACK THE OLD DESIGN!! OR AT LEAST FIX THE AS TAGS

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  




Click Here to Expand Forum to Full Width

HTML5 Development Center