Lambdas (also known as anonymous methods) provide a concise way to create functions and procedures that can be passed as arguments or assigned to variables.
DWScript supports both a modern arrow syntax for brief expressions and a more traditional block syntax for complex logic.
// Function lambda
var sqr := lambda (x: Integer): Integer => x * x;
// Procedure lambda
var log := procedure (s: String)
begin
PrintLn('Log: ' + s);
end;
// Traditional function syntax
var add := function (a, b : Integer) : Integer
begin
Result := a + b;
end; Lambdas are frequently used with standard library methods for filtering, mapping, and sorting data collections.
var list : array of Integer = [1, 2, 3, 4, 5];
// Map: Transform elements
var doubled := list.Map(lambda (x: Integer) => x * 2);
// Filter: Keep elements matching a condition
var evens := list.Filter(lambda (x: Integer) => x mod 2 = 0); A closure is an anonymous method that "captures" variables from its surrounding local scope.
Platform Difference: Variable capture (closures) is currently only supported when using the JavaScript Transpiler.
In Native Script Mode, lambdas cannot capture local variables from the outer scope. They must be self-contained or rely solely on their parameters.
In native mode, lambdas are excellent for pure functions, sorting logic, or any operation where the required data is passed in via parameters.
// Self-contained lambda works perfectly in native mode
var list : array of Integer = [3, 1, 4, 2];
list.Sort(lambda (a, b: Integer) => a - b);
PrintLn(list.Map(IntToStr).Join(','));
// What DOES NOT work in native mode (uncommenting will cause error):
// var factor := 2;
// var doubled := list.Map(lambda (x: Integer) => x * factor); // 'factor' is external to lambda 1,2,3,4
For developers targeting the web, DWScript lambdas are a powerful feature. The JavaScript transpiler maps them directly to native JavaScript closures and arrow functions.
When compiling to JavaScript, you can freely capture local variables. The transpiler ensures that the lexical scope is preserved, matching the behavior expected in modern web development.
// Supported in JS Mode (Commented out for native compilation check)
/*
function MakeCounter(start : Integer) : function : Integer;
begin
var count := start;
Result := lambda => Inc(count); // 'count' is captured
end;
*/