| AngelScript |

Anonymous functions

Anonymous functions, or lambdas as they are sometimes called, are functions that are declared locally for use with function handles.

The following is a quick demonstration on how to use anonymous functions.

      funcdef bool CMP(int first, int second);

      void main()
      {
        int valueA = 1, valueB = 2;

        bool result1 = func(valueA, valueB, function(a,b){ return a == b; });
        bool result2 = func(valueA, valueB, function(a,b){ return a != b; });
      }

      bool func(int a, int b, CMP @f)
      {
        return f(a,b);
      }

The anonymous function takes on the signature of the function handle it is assigned to, so the type of the arguments and the return type doesn't have to be explicitly declared.

It is not yet possible for anonymous functions to access variables declared in the same scope as the function, i.e. they cannot be used as closures.

If there are multiple matching uses for the anonymous function it will be necessary to explicitly inform the parameter types, so the ambiguity can be resolved.

      funcdef void A(int);
      funcdef void B(float);
      void func(A@) {}
      void func(B@) {}

      void main()
      {
        // Explicitly specify the type to tell the compiler that A is wanted
        func(function(int a) {});
      }