You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Lua中数值for循环变量的闭包行为疑问

Why Your Lua Closures Behave Differently in the For Loop

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 04:12:07