The following Python code:
def foo():
t = []
for i in range(1, 3):
def bar():
return i * i
t.append(bar)
return t
for f in foo():
print(f())
Outputs: 4 4. Why isn't the first call output 1? I thought the closure bar() could save the current value of i.
BTW, the almost equivalent Lua code:
function foo()
local t = {}
for i = 1, 2 do
local bar = function() return i * i end
table.insert(t, bar)
end
return t
end
for _, f in ipairs(foo()) do
print(f())
end
Outputs 1 4 as what I expected.