I've requested this once before, but I really think this should happen. Currently we have
anonymous functions, but they are a slight pain to use, because you can't use variables defined outside of the function without explicitly passing them in.
Function closures are when the environment outside of the anon functions are "closed" inside of them, letting you use the variables defined outside of the anon functions inside of them.
Extremely simple example:
PHP Code:
function foo() {
temp.a = 3;
temp.f = function (temp.x) {
return temp.x * temp.a;
}
temp.f(4); // would ideally return 12
}
In
temp.f, you should be able to access the
temp variables outside the anonymous function.
Note: You can set this variables to pass things in, but then you need to handle all the garbage collection yourself because the anonymous function can still exist after the surrounding function ends (i.e., by returning it). This is basically impossible since you don't know when the function is destroyed. It's also really messy and ugly.
An example where this would be useful:
PHP Code:
// takes a function and list, and returns a new list with that function applied to every element
function map(temp.f, temp.list) {
temp.newList = {};
for (temp.i = 0; temp.i < temp.list.size(); temp.i++) {
temp.newList.insert(temp.i, temp.f(temp.list[temp.i]));
}
return temp.newList;
}
function onPlayerChats() {
temp.a = int(player.chat);
temp.f = function (temp.x) {
return temp.x*temp.a;
};
temp.list = {1,2,3,4};
echo(this.map(temp.f, temp.list));
}
This
map function can already be defined. It is
temp.f that can't be defined yet.
When you chat "10", that should echo out "10,20,30,40".