November 28, 2006 Re: Idea: "Frozen" inner function | ||||
---|---|---|---|---|
| ||||
Posted in reply to Michael Butscher | Michael Butscher wrote: > David Medlock wrote: > > [What are closures?] > >>In my understanding, closures are like functions which carry state along with them. Like objects but with only a single method: opCall(). >> >>in Lua syntax: >> >>function make_adder() >> local sum = 0; >> return function(n) sum = sum + n; return sum; end >>end > > > What happens while the outer function is "alive" yet? > > E.g. something like (I don't know Lua, therefore I guessed syntax): As a testament to Lua, you guessed correctly... Javascript 1.5 syntax is very similar. > > function test() > local sum = 0; > local x = function(n) sum = sum + n; return sum; end > sum = 5; > print(x(5)); > end > > > Does this print 5 or 10? > > > > Michael When a stack frame is collected, upvalues(sum) are copied into the closure x. Sum will outlive the function test(), but won't be copied until you leave. I ran this in Lua 5.1: > test() 10 Obviously you need your copy semantics defined well to use them. This is why several functional languages make variables copy-on-write. For python this would be tuples, you can only make a new one not overwrite the old one. -DavidM |
Copyright © 1999-2021 by the D Language Foundation