Re: Nested functions - better example?
- Posted by petelomax Jan 13, 2021
- 846 views
The inner functions have access to the outer function's variables.
WHOAH! Alas not, since that would require a closure. Let me explain.
Bear in mind I've only just changed this, post-0.8.2, so all is not set in stone.
This summarises the current state of play (note I've just found some "static" issues, sidestepped here):
integer a = 'a' procedure p(integer b = 'b') static integer c = 'c' constant d = 'd' integer e = 'e' function f(integer g = 'g') static integer h = 'h' -- see PS constant i = 'i' -- "" string res = "" res &= a -- res &= b -- undefined res &= c res &= d -- res &= e -- undefined res &= g res &= h res &= i return res end function ?f() end procedure p()
The output is "acdghi". I've actually just modified the new hideScope() routine mentioned at the top of this thread to leave static and local(private) constants visible.
So, why are b and e "undefined"?
The reason is they are not in the current call stack frame. While in a simple case like the above they are only one "hop" away, that would not be true for any nested recursive routines.
Also, imagine that you save routine_id("f") somewhere, and invoke it after p() has exited - b and e would then simply no longer exist, anywhere.
There is a reason why nested functions lay broken for four years, and that be it.
You can of course pass b and e explicitly to f(), and if you like return and store them.
Anyone thinking I am just being stubborn or making this stuff up is invited to read http://jibbering.com/faq/notes/closures/
I will not accept any responsibilty for or pay for the removal of any stains caused by liquified brain cells dribbling out of anyone's ears after reading that, however it is actually very well written.
PS: I may yet have to ban nested static/constants such as h and i above, hopefully not, or at least hopefully not a great loss.