views:

28

answers:

2

this code is written in simple ActionScript, but i'm assuming this problem of mine would occur in all languages that have boolean datatypes.

i'm simply clicking the stage so that my boolean variable reverses its value and than traces/prints/logs it's new value. however, it's always tracing true instead of switching between true and false for each mouse click.

what am i doing wrong?

var myBool:Boolean;

stage.addEventListener(MouseEvent.CLICK, mouseClickHandler);

function mouseClickHandler(evt:MouseEvent):void
    {
    changeBoolean(myBool);
    }

function changeBoolean(boolean:Boolean):void
    {
    boolean = !boolean;
    trace(boolean);
    }
+3  A: 

In the function changeBoolean, you're changing the value of the boolean (poor name, by the way - try to avoid naming collisions with built-in types, even with different casing) parameter. This has no effect outside that function.

You want to change the value of myBool (which I would call a class field in .Net or Java) instead.

function mouseClickHandler(evt:MouseEvent):void
    {
    myBool = !myBool;
    trace(myBool);
    }

...is what I would do (again, with a naive understanding of ActionScript).

Michael Petrotta
+2  A: 

You are passing a value to the function, not the reference. This means that boolean value inside your changeBoolean function is copied from myBool variable so when you changed it inside the function, it didn't realy change myBool variable. There are basically two solutions to this:

  1. change the function to not accept parameters and inside it change myBool variable or
  2. change the function so that it returns the boolean parameter and on calling the function, set the myBool valu to the result of the function
Ivan Ferić
ah... makes sense. since i'm using many boolean variables i'll just reverse the boolean while i'm passing it's value: changeBoolean(myBool = !myBool);
TheDarkInI1978
i found this confusing because if i passed other objects, like display objects, to a function then i can change them. does this mean that primitive datatypes are only passed to functions as their value, while other non primitive datatypes are passed as themselves? is that the general rule?
TheDarkInI1978
Yes, value types are passed by value, while reference types are passed as references (and everything you do with them inside the function affects them outside the function as well). Reference types are generally classes, while value types are generally system types (boolean, integer, char, etc.), enums and structures.
Ivan Ferić