【问题标题】:Lua - Why does this not count each line printed?Lua - 为什么这不计算打印的每一行?
【发布时间】:2021-06-27 09:57:21
【问题描述】:

我一直在整理一些代码来对人们的考试分数进行排序,这样他们就可以看到他们的最高分数是多少以及他们何时完成的。我创建了以下代码,但它没有显示第 1、第 2、第 3 等计数器,我错过了什么?

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     

【问题讨论】:

    标签: lua


    【解决方案1】:

    不要在for 循环中使用local
    因为您在每次迭代中都将其声明为新的。
    ...从声明为local count的外部循环变成0
    如果循环中没有 local,您将更改并迭代外部声明的 local 变量。
    ...因此在循环中得到一个迭代的count

    【讨论】:

    • 简单!不好意思现在发布这个,非常感谢@koyaanisqatsi
    猜你喜欢
    • 1970-01-01
    • 2019-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-02
    • 2015-04-21
    • 1970-01-01
    相关资源
    最近更新 更多