tags:

views:

180

answers:

1

What is the difference between a closure and a nested closure? A good explanation with examples would be helpful.

+1  A: 

Scope of the variables and what environment they are bound to.

And how hard they are to implement in a compiler :)

ClosureA may be bound to it's local scope LA and parent-scope PA, then a closure inside that called ClosureB is bound to (potentially) LB, LA, PA

func a( v1,v2,v3 ){
    closure_b(bv1, bv2, bv3) { # Closure
        b_local1 = bv1
        b_local2 = v1  # parent scope

        closure_c(cv1, cv2) { # Nested closure has 'closure_b's scope too
            c_local1 = cv1
            c_local2 = bv1 # direct-parent scope
            c_local3 = v1 # parent's parent scope (nesting)
            c_local4 = b_local2
        }
        return closure_c;

    }
    return closure_b(); # closure_b() returns closure_c 
}
Aiden Bell
I follow everything in your code until the return statement. I didn't think closure_c was accessible outside of closure_b. Can you explain how closure_c can be returned from the scope of func a? Or is the return statement in this example incorrect?
adamjcooper
Typo in my case, will correct.
Aiden Bell
Great, thanks for the helpful example.
adamjcooper
No worries!.....
Aiden Bell