Re: Closures behaviour
Andrew Janke <[email protected]> Fri, 26 Feb 2021 13:54:58 -0500
| Newsgroups | gmane.comp.gnu.octave.maintainers |
|---|---|
| Message-ID | <[email protected]> |
On 2/26/21 12:43 PM, CdeMills wrote: > Hello, > > I had to revive some old code. Since I use more and more Python, I wanted to > use closure mechanisms to keep the computation cleaner. > > So I started refactoring the code, creating a main function which returns a > struct with a few function pointers. Those function pointers are initialized > to sub-funcs of the main function. According to MatLAB doc, the behavior is > that accessing the variable name in the subfunc has the effect of reading > the actual value from the parent environment. > > I tested a very small example from > https://research.wmz.ninja/articles/2017/05/closures-in-matlab.html which > works in Octave 6.2. Now, on my code, I noticed that only a small number of > variables from the parent is accessible from the innermost context. The most > basic symptom is that the number of variables returned by "who" shrinks in > the internal functions. > > I also tried under MatLAB 2018b, and all variables initialized before the > first function definition in the parent function are shared with all its > children. > > Is this some well-known behavior which will be aligned on MatLAB in the long > run ? > > Regards > > Pascal One minor point: > I also tried under MatLAB 2018b, and all variables initialized before the > first function definition in the parent function are shared with all its > children. I believe the Matlab behavior is actually "all variables initialized anywhere in the function", not just before the first nested function definition: Matlab's detection of variables in a function, and construction of the "static workspace" (which is what you get when a function has nested functions) is done at parse/compile time, not statement execution time. All variables that are assigned to at any point during function execution should be present during the entire function execution. I believe that your expectation that all variables in the parent function, not just those explicitly referenced with static code in the nested function, should be available in the nested function's workspace is correct with respect to Matlab behavior. (E.g. they are valid targets for assignment using "eval" and similar dynamic assignment mechanisms, as long as they are _also_ explicitly initialized using static code.) Though I can't find explicit support for this in the Matlab docs. References: * https://www.mathworks.com/help/matlab/matlab_prog/nested-functions.html * https://www.mathworks.com/help/matlab/matlab_prog/variables-in-nested-and-anonymous-functions.html I can't speak to Octave's long run goals here. Cheers, Andrew