Search code examples
lua

Lua - Why does this not count each line printed?


I’ve been putting a bit of code together to sort people’s test scores, so they can see what their highest is and when they did it. I created the following code but it does not show a counter of 1st, 2nd, 3rd etc., what am i missing ?

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

It prints the following, with everything showing 1, when it should be 1, 2, 3 etc.

1     17     Ben     
1     16     Ben     
1     14     Ben     
1     12     Ben     
1     12     Ben     
1     12     Ben     
1     12     Ben     
1     12     Ben     

Solution

  • Simply dont use local in the for loop.
    Because you declare it new in each iteration.
    ...that becomes the 0 from the outside loop declared local count
    Without the local in the loop you change and iterate the outside declared local variable.
    ...and get therefore an iterated count in loop.