The use of Cocos2d-x v3.0 lambda expressions

Source: Internet
Author: User




The C ++ 11 feature is introduced in Cocos 2d-x 3.0. This includes the Lambda object used in the callback function.

Let's take a look at the code in TestCpp:


Three Lambda expressions are used in the callback function of the touch event:

[] (Touch * touch, Event * event ){};

The following describes how to use Lambda expressions.


Under normal circumstances, if we need to use the same operation in many places, we should usually define a function to implement this function.

In some cases, we only need to use some simple operations in one or two places, and do not want to define this function name, then we can use Lambda expressions to implement our functions.


A complete lambda expression is expressed as follows:

[Capture list] (parameter list)-> return type (function body)

[Capture list] (parameter list)-> return type (function body)

So why is the form of Lambda expression in the figure different from the above?

The reason is that the parameter list and return type of the Lambda expression are and can be ignored, but the capture list and function body must contain.


That is to say, a Lambda expression is actually an anonymous function. Its advantages are similar to that of inline functions (embedded functions and built-in functions), but Lambda expressions may be defined inside the function.

So what are the advantages of inline functions? Let's give an example. For example, our program has the following code:

Void (){

... // Function body


Void main (){

... // Omitted

A (); // call function

... // Omitted


The main process of code execution is as follows:

1. after executing the statement before calling function A, the main function needs to record the currently executed command address before calling function, it is used to continue executing subsequent code after executing function.

2. Then, the control of the process will be transferred to the entry of function A, and the statements in function A will be executed.

3. After the execution is completed, the process will be returned to the previously recorded address, and the on-site operations will be resumed based on the previously recorded information to ensure normal execution of the program.


Each operation in the above process takes A certain amount of time. If function A needs to be frequently used, it will take A long time, resulting in reduced efficiency.

To solve this problem, C ++ provides inline functions. The so-called inline function is to declare a function as an inline function, so that during compilation, directly copy the called function body to the main function, instead of converting the process to this function, to reduce the running time of the program.

This is because when the size of a function is very small, the time overhead in the function call process will exceed the time required to execute the function.


This is the benefit of using inline functions. For Lambda expressions, we can understand them as an unnamed inline function.


Next we will analyze the lambda expressions one by one:

1. "[capture list]"

First, observe the difference between the first lambda expression and the capture list of the third lambda expression.

As you can see, the capture list in the first expression is blank [], while the capture list in the third expression contains an equal sign [=].


Next, let's take a look at the variables used in the first and third lambda expressions.

We can see that all the variables in the first expression are defined in the Lambda expression (except log, because log functions are included in the header file ),

The variables sprite1 and sprite2 used in the third expression are not defined in the lambda expression, but are the variables in the current function or the current class.

We can conclude that external variables cannot be accessed in the Lambda Expression Function body. If you want to use variables defined by the function in vitro, You need to capture them, the third lambda expression uses "Value capture", which corresponds to another "Reference capture ".

[]: Empty capture list, that is, lambda expressions cannot use variables in the function

[=]: Value capture, that is, lambda expressions can be copied to access the value of a variable in the function.

[&]: Reference capture, that is, the variables in the functions used in lambda expressions are referenced.

When we do not want to capture all the variables, we can use the following methods to capture them, for example:

[= Sprite1, & sprite2]

Here we only capture two variables. The first one is captured by copying values, and the second is captured by reference. Variables and variables are separated by commas.


Under normal circumstances, if a variable is a value copy, Lambda cannot change its value. If we want to change the value of a value copy variable, we need to add the keyword mutable before the parameter list.

For example:
Auto s1 = 10;

Auto s2 = [= s1] () {return ++ s1}; // error. Because s1 is a value copy, the value of s1 cannot be changed.

Auto s2 = [= s1] () mutable {return ++ s1}; // correct

2. (parameter list)

When passing parameters in a Lambda expression, you must note that the Lambda expression cannot have default parameters, that is, the real parameters of the Lambda expression must be equal to the shape parameters.

In other cases, the parameter part of the Lambda expression is no different from that of a common function. It is generally used in conjunction with STL.

For example:

Void Test (){

Vector MyVec; // create an int-type container

MyVec. push_back (1); // insert data 1

MyVec. push_back (2); // insert data 2


Int a = 10; // create a local variable

For_each (myVec. begin (), myVec. end (), [&] (int v) mutable (cout <

Cout <


3.-> return type

We have mentioned that the return value of Lambda can be omitted.

The reason is that the compiler will deduce the return value based on the return type, but if you need return and then perform another type conversion, we can write a return type.

For example, cout <[] (float f) {return f} (1.5); // here we pass 1.5 as the parameter and print it. The returned result is the value of the real parameter 1.5.

Cout <[] (float f)-> int {return f} (1.5); // We forcibly convert the return value to int and output the result to 1.


4. Function body

There is no difference between the function body and the common function. We only need to pay attention to the above points and there will be no problems in the function body.


Now let's look back at the touch event in TestCpp, so we can understand the truth.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.