https://discordapp.com/channels/918498540232253480/918498540232253483/1036427638715203656
Hi, can someone elaborate on the syntax for the following mqtt.Client code, I am not sure how this starts as a task, as anormal task is started with task:: and all I see here is ::
client = mqtt.Client --transport=transport --routes={
TOPIC: :: | topic payload |
// Do something with topic and payload
}
This, by itself, doesn't start a task yet.
All this does, is tell the client that it should route messages to TOPIC to the lambda (:: | topic payload | ...).
The task is only created when you call client.start.
Got it: I stiil don't understanf what a lambda is ..
That task then receives messages, and then uses the routes-map to dispatch incoming messages accordingly.
A lambda is a function of JavaScript.
In C++ this would be a [&]() { ... }
(although better than that, as it the variables it refers to are kept alive, whereas C++ would barf).
So it's a pointer to function of code ..
In Python anonymous functions are actually called "lambda" too.
Pretty much.
The :: print "foo" becomes an object that has a call method that then executes the code print "foo".
You can play with it:
main:
x := 499
my_lambda := ::
print x
x++
my_lambda.call // => 499
my_lambda.call // => 500
(edited)
The nice thing about lambdas is that they can use local variables, and make sure that these stay alive.
This is, why we sometimes use blocks (: print "in a block") vs lambdas (:: print "in a lambda").
Fundamentally, lambdas are more flexible, as you can return them or store them in globals, maps, ...
However, they are more expensive, which is why we prefer to use blocks in most places instead.