lua-users home
lua-l archive

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


I'm curious: what languages would print 1 and 2 below? I can't think of one.

The equivalent Scheme,

   (define (inc i) (lambda (n) (+ n i))
   (define i 1)
   (define inc1 (inc i))
   (inc1 0)
   (set! i 2)
   (inc1 0)

should never ever print anything other than 1 and 1.

On Tue, Oct 23, 2012 at 2:01 PM, spir <denis.spir@gmail.com> wrote:
> Hello,
>
> In most languages with function closures, the following piece of code would
> print 1 and 2:
>
> inc = function (i)
>    return function (n) return n+i end
> end
>
> i = 1
> inc1 = inc(i)
> print (inc1(0))
>
> i = 2
> print (inc1(0))         --> 1 or 2 ?
>
> The reason is that so-called upvalues usually not are values, but "up-vars".
> In fact, what the closure closes on is the variable, here i, not its piece
> of data [1]. Anyway, this is very common [2], some even call this behaviour
> only "true" closures. (This may have fit well in Lisps of the dynamic
> scoping flavour.)
>
> Seems like Lua does (what I consider) the right thing, here. How are
> closures really built and what is there theoretical semantics on this point?
> (I did not really find answers in docs).
> Also, has anything changed in Lua recently about this question?
>
> Thank you,
> Denis
>
> [1] No idea why one would want that, since it kind of implicitely breaks
> referential transparency (the func now really depends on an external var),
> and maybe even lexical scoping (depending on how you understand it).
>
> [2] An exception is OCaml, not because upvalues are values, but because the
> second assignment would create a new *variable*, thus unrelated to the
> closure.
>