#Referencing variables within Func Scope

1 messages · Page 1 of 1 (latest)

dreamy ermine
#

so I noticed that when you make a function, it doesn't seem to have access to the scope above it. The pictured example is trivial, I know, but how do I make it so I can capture something from the upper scope into a closure like this?

My specific use case was using the array function that allows you to pass in a function which takes index to construct all the members, but I need information from outside that to properly create all the members.

calm plinth
#

gm unfortunately does not have closures right now

#

the workaround is using method which can bind the scope the function executes in to a struct, like so:

function someFunc(whatever) {
    return method({ whatever }, function() {
        return watever * 2;
    });
}
#

its not the end of the world but it may catch you out if you need to do stuff like access instance variables on the instance calling this function, since you've effectively changed the context the function runs in to where self now refers to the struct passed into the first argument of method

#

its basically like going with ({ whatever }) { the_function() } when you run that returned function

dreamy ermine
#

Much nicer than using a nested for.

calm plinth
#

ya, method is very useful for all the new array functions and whatnot

#

as for currying, this is kinda the best we've got at the moment:

var thingo = method({ some_data }, function(a, b) {
    return some_function(some_data, a, b);
});

thingo(2, 3);
dreamy ermine
#

I was never the best with this lambda manipulation anyway. One more thing, are you just using JS syntax highlighting in your code blocks to cheat, or what?

calm plinth
#

its got gml

#

```gml

```

#

but i often fall back to specifying js since it often has better highlighting anyway

#
var thingo = method({ some_data }, function(a, b) {
    return some_function(some_data, a, b);
});

thingo(2, 3);```
#

looks a bit nicer

#

but the gml one also highlights built in functions (though its pretty outta date)

#
show_debug_message("something");```
dreamy ermine
#

Why on earth does it have gml....

calm plinth
#

its using an open source library for its highlighting

#

discord didnt make it