0

From the docs for ESP8266WebServer here https://github.com/esp8266/Arduino/tree/master/libraries/ESP8266WebServer its shows server.on syntax like this

server.on("/", handlerFunction);

I don't understand what this line is doing.

server.on ( "/admin.html", []() { Serial.println("admin.html"); server.send ( 200, "text/html", PAGE_AdminMainPage );   }  );

I specifically do not understand what the []() is. The rest of it I get.

M.M
  • 138,810
  • 21
  • 208
  • 365
TheEditor
  • 486
  • 1
  • 4
  • 18

1 Answers1

1

This is what's known as a "lambda expression". It's something that C++ and many other languages support (C does not).

Lambda expressions are used to allow languages to manipulate functions. In this case, the lambda expression lets you use an "anonymous function" so that you can pass a handler to server.on() without having to declare it as a function with a name ahead of time.

The [] part lets you specify "captures" - variables which will be available to the lambda function. The () part is the normal list of function parameters that you'd have when you declared a function. And the {} part is of course the function's code.

In this case, no captures, no parameters, so []() { code... }.

You can read more about C++ lambda expressions at https://en.cppreference.com/w/cpp/language/lambda#Syntax

romkey
  • 6,218
  • 3
  • 16
  • 12