[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Closure failure? [ How they work ]

Pat <pat@pat.net> writes:

> I can see how this would be confusing, but I'm afraid that it's currently
> the expected behavior.  The problem with loosening up the language such that
> you don't have to declare variables is that you don't have a clear way to
> determine where they are intended to be declared vs. where they are simply
> being assigned.  The most general solution (and the one that BeanShell
> currently uses) is that variablas are declared wherever they are assigned
> and if you want to assign a variable in a parent scope you have to use a
> modifier...

The observed behaviour is still sort of odd.

I haven't managed to grovel through enough of the interpreter to
verify this, so could you check my reasoning here:

- The first use (rvalue, in the first print) is resolved to x in the
  scope of ctest().

- The second use (rvalue, in "x + 1") resolves the same way.

- The third use (lvalue, in "x = x + 1") causes the creation of a new
  variable in the scope of subfunc() and assigns the value there. 

- The fourth use (rvalue, in the second print) resolves to the
  newly-minted x in the scope of subfunc().

If this is right, it's really the generation of the new binding in the
third use that seems goofy. Why is it necessary to create the new
local binding when you can test for the existence of a binding in an
outer scope?

> I agree that this is not linguistically pleasant and it bothers me that it
> diverges from Java in a sense...  however Java doesn't allow defining methods
> within methods, so it's not entirely divergent.

I guess if you don't count local and anonymous classes (reasonable,
since they don't support real closures either).

        - Nathan