Tutorial 8. Lambdas and exceptions
How create a lambda or a closure
- Make a lambda like in the usual JavaScript code.
- Don't declare any variables.
In a closure, we have access to the outside variables. Here, we read variable a. We will see this when we build and run the project.
18
There is an assignment in the closure lambda. We don't need to put a var keyword there because Drakon.Tech will declare a variable automatically. Keep in mind that the code generator will declare the variable in the containing function, not in the lambda. We can see it in the code.
function lambda() { var a, closure, foo, result; a = 10 closure = function (x) { foo = a + x return foo } result = closure(8) console.log(result) }
What about other JavaScript statements? Can we use if and for constructs inside lambdas in Drakon.Tech? Technically, it is possible but strongly discouraged. The presence of if and for constructs in a lambda implies an algorithm with nontrivial control flow. Algorithms belong to flowcharts, not to lambdas.
What to do if we must have a complicated algorithm in a lambda?
- Move the algorithm in a separate function. Create a DRAKON flowchart for that.
- Create a one-line lambda.
- Call that new function in the lambda.
Lambdas and closures bring tremendous power, but that power comes at a cost. Every time the reader encounters a lambda in the code, they pay a significant mental price. Keep lambdas as short and straightforward as possible.
How to catch an exception
- Make a try-catch construct inside an Action icon like in the usual JavaScript code.
- Don't declare any variables.
All values assigned in a try-catch block will be available later in the function.
Here, the foo variable will keep its value outside of the try-catch block.