SOLVED Variable scope

kalzme

Member
Hey,

In javascript I could write something like this:
JavaScript:
function test(callback) {
    var wrappedCallback = function() {
        alert("WRAPPER");

        if (callback != null) {
            callback();
        }
    }
    
    wrappedCallback();
}

test(function() {
    alert("CALLBACK");
});
where the callback parameter that is passed to the first function will also exist in the wrappedCallback function defined inside of that function.

However, whenever I try to do something like this in Game Maker, it crashes saying it can't find the callback variable.
I imagine this has to do with the way Game Maker scopes variables, but is there any way around this?
 

Binsk

Member
You could just set a 'member' variable in the function to the parameter and access that instead. Not perfect but it allows the scope you are looking for. For example:
GML:
function test(_callback) {
    callback = _callback; // <-- Store in a variable that has the scope you want
    var wrappedCallback = function() {
        alert("WRAPPER");

        if (callback != null) {
            callback();
        }
    }
    
    wrappedCallback();
}

test(function() {
    alert("CALLBACK");
});
 

kalzme

Member
Great, that indeed works!

GML:
global.RequestMaker = {
   
    RequestOne: function (_callback) {
        callback = _callback;
       
        do_request("http://url-of-request-one.com", function() {
                      // Some other stuff
                      callback();
             });
    },
   
    RequestTwo: function (_callback) {
        callback = _callback;
       
        do_request("http://url-of-request-two.com", function() {
                      // Some other stuff
                      callback();
             });
    },
}
This is what my code sort of looks like.
Just to make sure I understand what's happening:
imagine I'd call
global.RequestMaker.RequestOne(...);
global.RequestMaker.RequestTwo(...);

then request 1 would add callback to the global.RequestMaker struct as a variable and put the _callback value there
and request 2 would overwrite that value with the parameter that it got passed, right?
 
Last edited:

NightFrost

Member
You also could write it like:
GML:
function test(callback){
    wrappedCallback = function(cb){
        if(cb != undefined){
            cb();
        }
    }
    wrappedCallback(callback);
}

test(function(){
    show_debug_message("CALLBACK");
});
By sending the data to the scope where it is needed you don't need to temp store it.
 
Top