Please explain syntax - [](AsyncWebServerRequest *request){

    server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
        request->send(200, "text/plain", "Hello, world");
    });

looks like the 3rd argument may be a ptr to AsyncWebServerRequest.

i don't understand the "[]" preceding it?

i don't understand what looks like function body following it?

It is a lambda expression, sort of an unnamed function.

can it be replaced with a more conventional function ptr?

Yes, I think so, let me check.

It seems to consume a parameter of type ArRequestHandlerFunction, which is defined as follows.

typedef std::function<void(AsyncWebServerRequest *request)> ArRequestHandlerFunction;

So perhaps you can try to use a callback function like this:

void callback(AsyncWebServerRequest *request) {
  request->send(200, "text/plain", "Hello, world");
}
1 Like

Acts like:

void RootFolderHandler(AsyncWebServerRequest *request)
{
  request->send(200, "text/plain", "Hello, world");
}

    server.on("/", HTTP_GET, RootFolderHandler);

The lambda expression is handy when you need the address of very short function just to pass it to another function.

1 Like

thanks

so the "[] " is identifying it as a lambda expression?

That is how I recognise it, but there can be something in between the brackets. This is explained in the "Lambda capture" section of the link I posted. The full syntax is also explained there (at the top of the page).

i saw that -- " The captures is a comma-separated list of zero or more captures"

i'd like to see something that describes how to use lamda expressions productively

Here are a couple of examples.

it actually tells which variables will be made available to the function when it runs (it 'captures' those variables)

A lambda can only be converted to a function pointer if it does not capture any variable.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.