[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: upvalues actually are values?
- From: Coda Highland <chighland@...>
- Date: Tue, 23 Oct 2012 12:05:44 -0700
On Tue, Oct 23, 2012 at 11:41 AM, spir <denis.spir@gmail.com> wrote:
> On 23/10/2012 20:19, Johann Hibschman wrote:
>>
>> 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.
>
>
> I was messing up 2 issues. The (simpler) example that shows the behaviour I
> had in mind is:
>
> i = 1
> inc1 = function (n) return n + i end
>
> print (inc1(0))
>
> i = 2
> print (inc1(0))
>
> And yes, now Lua also print 1 and 2.
> Seems crazy to use this "feature", but I actually was caught once when
> writing a "method" outside the table defining the "type", which depended on
> a global acting as a kind of setting. Tgat's how I discovered the point.
> Now, why people find it more useful than dangerous (that closures close on
> vars, not data), I don't know. Also, it seems more complicated to implement,
> doesn't it?
>
> Denis
>
In a dynamic language where everything's a reference anyway, I can't
imagine it's that hard. Among other things, since there's ALREADY a
scope chain that has to work, having upvalues by reference instead of
upvalues by value means you don't have to introduce a way to store
stuff by value.
It's also incredibly useful; this is how you implement the equivalent
of "static" locals in C/C++, or how you hide the internals of an
object without making it immutable.
Now admittedly it's not particularly FUNCTIONAL, but Lua never claimed
to be a functional language.
/s/ Adam