Lua - 为什么这不计算每行打印的数量?

我正在编写一些代码来对人们的测试成绩进行排序,以便他们可以看到他们的最高成绩和何时获得。我创建了以下代码,但它没有显示第1,第2,第3等的计数器,我缺少了什么?

local tt ={}

local verbalreasoning = {
    { test=1, name="Ben", res=12, testdate="6月20日" },
    { test=2, name="Ben", res=12, testdate="6月21日" },
    { test=3, name="Ben", res=12, testdate="6月22日" },
    { test=4, name="Ben", res=14, testdate="6月23日" },
    { test=5, name="Ben", res=12, testdate="6月24日" },
    { test=6, name="Ben", res=17, testdate="6月25日" },
    { test=7, name="Ben", res=16, testdate="6月26日" },
    { test=8, name="Ben", res=12, testdate="6月27日" }
}

for _, v in ipairs(verbalreasoning) do
    table.insert(tt, { myres=v.res, myname=v.name, mydate=v.testdate })
    end

table.sort(tt, function(a,b) return a.myres > b.myres end) -- 根据最高分排序

local count = 0
local increment = 1

for _,v in pairs(tt) do
    local count = count + increment
print(count, v.myres, v.myname, v.testdate)
end

它打印出以下内容,所有内容都显示为1,当它应该是1,2,3等。

1     17     Ben
1     16     Ben
1     14     Ben
1     12     Ben
1     12     Ben
1     12     Ben
1     12     Ben
1     12     Ben
点赞
用户11740758
用户11740758

简单来说,在 for 循环中不要使用 local

这是因为每次迭代都会新声明它。

这样就从外部循环中声明的 local count 变为了 0

如果在循环中没有使用 local,则会更改和迭代外部声明的 local 变量。

因此,在循环中会得到一个递增的 count

2021-06-27 10:59:54