5 ms·
The syntax is not the prettiest, but it is legible once you understand what [](){} means. In C#, there is no such thing, but there is a part of me that wishes
by partisan 10y ago
The syntax is not the prettiest, but it is legible once you understand what [](){} means.
In C#, there is no such thing, but there is a part of me that wishes we had such a thing. I like the ability explicitly state what variables are being captured.
- rtpg 10y agoI'm not 100% sure, but C#'s compiler should automatically capture what you need (and leave out the rest). I think the primary need for manual declaration is because in C++ you need to differentiate between pass by copy semantics and pass by reference semantics.
- noblethrasher 10y agoYep, in Microsoft’s C# compiler, only the closed over local variables of a function are captured (which, in C#’s case, means generating a class with fields corresponding to each closed over local, and then replacing those locals with references to their respective fields of an instance of that class).
- masklinn 10y ago> I think the primary need for manual declaration is because in C++ you need to differentiate between pass by copy semantics and pass by reference semantics. That's not actually a need, C++ includes [=] and [&] (capture everything by value or by reference). You can get a mix by creating references outside the body then capturing the environment by value (capturing the references by value and thus getting references). On the one hand it has a bit more syntactic overhead (you have to take and declare a bunch of references before creating the closure), on the other hand there's less irregularity to the language, and bindings mean the same thing in and out of the closure. FWIW that's what Rust does[0], though it may help that Rust's blocks are "statement expressions", some constructs would probably be unwieldy without that. [0] the default corresponds to C++'s [&] (capture by ref), and a "move closure" switches to [=] instead
- masklinn 10y ago> I like the ability explicitly state what variables are being captured. Why? You state what variables are being captured by just using them in the lambda body.
- jlebar 10y ago> You state what variables are being captured by just using them in the lambda body. Wow, have you never spent a week debugging a JavaScript memory leak?
- masklinn 10y agoNo. What I have done on the other hand was add unused lexical variables to an anonymous function so the runtime wouldn't optimise them out of the closure and I could still see them in the debugger.
- spdionis 10y agoPHP also doesn't capture variables by default (except $this) and i like it that way.