[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: upvalues actually are values?
- From: Xavier Wang <weasley.wx@...>
- Date: Wed, 24 Oct 2012 02:09:06 +0800
No, Lua is not what your think, but just the "true" upvalue you mean,
i.e. Lua's upvalue is indeed "upvars".
the main issue in your code, is that the upvalue "i" is not the global
var "i", but the argument of function inc "i".
maybe you can try this:
local i
inc = function ()
return function (n) return n+i end
end
i = 1
inc1 = inc(i)
print (inc1(0))
i = 2
print (inc1(0)) --> 1 or 2 ?
notice that it really print 1 and 2, there are only one i in this
situation, not global "i" and upvalue "i".
2012/10/24 spir <denis.spir@gmail.com>:
> 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.
>
--
regards,
Xavier Wang.