Lua中数值for循环变量的闭包行为疑问
Let's break down the two cases to explain the differing outputs.
First Snippet: Shared Local Variable
In your first code block, both t1 and t2 close over the same local variable a:
local a = 1 t1 = function() return a end a = 2 t2 = function() return a end
When you update a to 2, both functions reference this single variable. That's why both print(t1()) and print(t2()) output 2—there's only one a to read from.
Second Snippet: Numerical For Loop's Special Behavior
Your for loop uses Lua's numerical for construct, which handles the loop variable i differently than a manual variable assignment.
Lua's numerical for loop creates a separate local binding of i for each iteration. That means each function you store in the table closes over a distinct i variable, each holding the value from that specific iteration (1 for the first loop, 2 for the second).
To contrast, here's what happens with a manual while loop using a single reused variable:
table = {} local i = 1 while i <= 2 do table[i] = function() return i end i = i + 1 end print(table[1]()) -- Outputs 3 print(table[2]()) -- Outputs 3
Here, both closures reference the same i variable, which ends up as 3 after the loop. But the numerical for loop avoids this by giving each iteration its own i, so each closure captures the value you expect.
That's why table[1]() returns 1 and table[2]() returns 2—each function is tied to the unique i from its loop iteration.
内容的提问来源于stack exchange,提问作者Tobias Gierke

