Historical forum-msg-id-135469-edit, Revision 1

Original date:2021-01-13 12:02:43 Edited by: petelomax Subject: Re: Nested functions - better example?

katsmeow said...

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' 
        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 
end procedure 

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.

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.

Not Categorized, Please Help


Quick Links

User menu

Not signed in.

Misc Menu