How do I alter a passed variable?

I’m trying to gain the ability to change a BOOL variable from false to true within a function of another file. The variable in this case is named “messFin”. I can’t get it to register as true in the main file.

Here’s the call to the function in the main file (main.hx):

    south = 10;
    east = 5;
    c = 0;
    messFin = false;
    Messages.ShowMess(south, east, mess, messFormat, messPage, messFin, c);
    trace(messFin);

Here’s the code for the 2nd file (messages.hx):

    package;
    import openfl.text.TextField;
    import openfl.text.TextFormat;


    class Messages
    { 
	public static function ShowMess(south:Int, east:Int, mess:TextField, messFormat:TextFormat, 
			messPage:Int, messFin:Bool, c:Int):Void {   //c is which colPerson hit
				
			
		if (south == 10 && east == 5 && c == 0) {
			mess.text = "What are you doing this far west of xxx?";
			messFin = true;
		}
	    }
    }

Certain kinds of variables are copied when you call a function, rather than “passed by reference”. Simple types, such as Int, Float, String or Bool are copied, while object types are passed by a reference.

function modifyValues (a:Int, b:Float, c:Bool, d:String, e:Dynamic) {
    a++;
    b++;
    c = !c;
    d += " world";
    e.val += 100;
}
var a = 1;
var b = 2.222;
var c = false;
var d = "hello";
var e = { val: 100 };

modifyValues (a, b, c, d, e);

trace (a); // 1
trace (b); // 2.222
trace (c); // false
trace (d); // hello
trace (e); // { val: 200 }

Within the function you call, when you change the value of a basic type, it is changed within that function, but it does not affect the original value outside the function. To do that, you will either want to pass objects, and change the value on an object, or you may want to use a public static variable

function setName (sprite:Sprite) {
    sprite.name = "Fantastic";
}
var sprite = new Sprite ();
setName (sprite);
trace (sprite.name); // Fantastic

or

class DoWork {
    
    public static var complete:Bool = false;
    
    public static function work ():Void {
        
        complete = true;
        
    }
    
}
trace (DoWork.complete); // false
DoWork.work ();
trace (DoWork.complete); // true

You can also use a return value

function opposite (value:Bool):Bool {
    return !value;
}
var value = false;
trace (value); // false
value = opposite (value);
trace (value); // true
1 Like

Great insight, thanks for the detail. What you said makes a lot of sense. I’ll try to return method first. Thank you.