10.5. Closures
LuneScript supports closures.
// @lnsFront: ok
fn func( mut val:int ): form {
return fn () {
val = val + 1;
print( val );
};
}
let sub1 = func( 10 );
sub1(##); // 11
sub1(##); // 12
sub1(##); // 13
sub1(##); // 14
let sub2 = func( 100 );
sub2(##); // 101
sub2(##); // 102
sub2(##); // 103
sub2(##); // 104
The above function func()
is a function that creates and returns a closure. This closure is a function that increments the argument val of func and outputs it.
In this sample, func(10) and func(100) are called, the closures generated by each are set to sub1 and sub2, and called 4 times each. This will output 11-14, 101-104.