Lua - 为什么这不计算打印的每一行?
Lua - Why does this not count each line printed?
我一直在整理一些代码来对人们的考试成绩进行排序,这样他们就可以看到他们的最高分是多少以及他们什么时候做到的。我创建了以下代码,但它没有显示 1st、2nd、3rd 等的计数器,我错过了什么?
local tt ={}
local verbalreasoning = {
{ test=1, name="Ben", res=12, testdate="June 20" },
{ test=2, name="Ben", res=12, testdate="June 21" },
{ test=3, name="Ben", res=12, testdate="June 22" },
{ test=4, name="Ben", res=14, testdate="June 23" },
{ test=5, name="Ben", res=12, testdate="June 24" },
{ test=6, name="Ben", res=17, testdate="June 25" },
{ test=7, name="Ben", res=16, testdate="June 26" },
{ test=8, name="Ben", res=12, testdate="June 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) -- sort highest to lowest
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
不要在 for
循环中使用 local
。
因为你在每次迭代中都声明它是新的。
...从声明为 local count
的外部循环变成 0
如果循环中没有 local
,您可以更改并迭代外部声明的 local
变量。
...因此在循环中得到一个迭代的 count
。
我一直在整理一些代码来对人们的考试成绩进行排序,这样他们就可以看到他们的最高分是多少以及他们什么时候做到的。我创建了以下代码,但它没有显示 1st、2nd、3rd 等的计数器,我错过了什么?
local tt ={}
local verbalreasoning = {
{ test=1, name="Ben", res=12, testdate="June 20" },
{ test=2, name="Ben", res=12, testdate="June 21" },
{ test=3, name="Ben", res=12, testdate="June 22" },
{ test=4, name="Ben", res=14, testdate="June 23" },
{ test=5, name="Ben", res=12, testdate="June 24" },
{ test=6, name="Ben", res=17, testdate="June 25" },
{ test=7, name="Ben", res=16, testdate="June 26" },
{ test=8, name="Ben", res=12, testdate="June 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) -- sort highest to lowest
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
不要在 for
循环中使用 local
。
因为你在每次迭代中都声明它是新的。
...从声明为 local count
的外部循环变成 0
如果循环中没有 local
,您可以更改并迭代外部声明的 local
变量。
...因此在循环中得到一个迭代的 count
。