[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: "dynamic" closures
- From: spir <denis.spir@...>
- Date: Mon, 30 Nov 2009 12:12:09 +0100
Hello,
Was trying to understand Lua closures better (the indications in historical docs are not enough for my limited brain), when I stepped on this:
x = 1
function f()
n = 1
function g(a)
print (x + n + a)
end
return g
end
g= f()
g(1) --> 3
x = 2
g(1) --> 4
I'm a bit surprised the code works "as unexpected" ;-) As a consequence, g becomes totally referentially "opaque", or do I misinterpret? (Maybe I miss a basic point, but for me this smells strong like naughty bugs. Even more since x is a global.) Do you have use cases for such an idiom (that could hardly be refactored into harmless expression)?
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
(*) by name, indirect access, second table lookup
(**) by address, direct access, no second lookup
________________________________
la vita e estrany
http://spir.wikidot.com/