(mapc (lambda (x) (funcall x))This outputs:
(loop for i from 1 to 3 collect
(let ((localvar i))
(lambda ()
(format t "loop:~a, local:~a~%" i localvar)))))
loop:4, local:1which makes sense to me, now that I've been working in Common Lisp. Inside the inner lambda, i refers to the loop variable, which is at 4 at the end of the loop. During each iteration of the loop, a new binding is created for localvar, and then the inner lambda closes over it. That's why we have different values for local but the same value for loop.
loop:4, local:2
loop:4, local:3
However, the closest equivalent I can manage in Lua is this (apologies for the temporary):
collection={}And this outputs:
for i=1,3 do
collection [i] = function ()
local localvar = i
print("loop:" .. i .. ", local:" .. localvar .. "\n")
end
end
for k,v in pairs (collection) do
v()
end
loop:1, local:1So, it looks like Lua actually closes over the value, whereas Lisp closes over the binding. I'm trying to think of a way to force Lua to close over the binding by boxing the value or something, but I'm coming up dry.
loop:2, local:2
loop:3, local:3
No comments:
Post a Comment