[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: "dynamic" closures
- From: spir <denis.spir@...>
- Date: Tue, 1 Dec 2009 09:27:57 +0100
Mark Hamburg <email@example.com> dixit:
> > About implementation, it seems to indicate Lua embebs symbolic references (*) to outer _variables_ in reachable scopes, when creating a closure for g0. Not pointer references (**) to _values_; otherwise the replacement of x would not be seen by the closure. Before trying, I thought the outcome would be 3, meaning values are kind of frozen at closure creation time (would be the case if references were pointers).
> > [I imagine this behaviour may match the one of closures in functional languages (?), but anyway the whole paradigm is so different...]
> > Denis
> This is exactly how true closures work in all languages with closures. The creation of g closes over the references to n and x (which as you've written them are global but might as well be local -- you'll get the same results). If you use local variables, a new instance of n is created whenever x is executed, but there is presumably only one point where x is created hence all references lead back to the same value.
> Perhaps you have experience with a poor man's closure implementation in which the values are copied into the closure at the time the closure is created? That meets many of the needs of a closure, but it is just a weak copy. Consider for example wanting to write:
> local sum = 0
> table.foreachi( array, function( i, v ) sum = sum + v end )
> print( "Sum = ", sum )
> In order for this to work, the reference to sum in the function have to refer to the mutable variable declared outside the function.
Thank you, your explaination makes things much easier. I like the expression "mutable variable", as it clear highlights that what is referred to by the closure is indeed a variable (while the _value(s)_ may even be immutable, like in your example).
All this was difficult for me, I guess, because usual references are (masked) pointer; Ids are adresses. If upvalue where identified by address, the code above wouldn't work, I guess.
May I suggest that upvalues are analog to parameters passed by name? (which is indeed not Lua's paradigm)
la vita e estrany