Lua Gradebook Report
A gradebook report is a summary that lists each student with an average score and a letter grade. This project builds the full report from a table of students, sorts it by name, and ends with the class average.
average turns three scores into 91.0
average adds 90, 92, and 91 to get 273, then divides by 3. The formatted print shows 91.0.
local function average(scores)
local total = 0
for i, v in ipairs(scores) do
total = total + v
end
return total / #scores
end
local scores = {90, 92, 91}
print(string.format("%.1f", average(scores)))grade gives a letter for two averages
grade checks an average against the letter bands from the top down. The two calls print A for 91 and D for 67.
local function grade(avg)
if avg >= 90 then
return "A"
elseif avg >= 80 then
return "B"
elseif avg >= 70 then
return "C"
else
return "D"
end
end
print(grade(91))
print(grade(67))Example
local function average(scores)
local total = 0
for i, v in ipairs(scores) do
total = total + v
end
return total / #scores
end
local function grade(avg)
if avg >= 90 then
return "A"
elseif avg >= 80 then
return "B"
elseif avg >= 70 then
return "C"
else
return "D"
end
end
local students = {
{name = "Mia", scores = {90, 92, 91}},
{name = "Sam", scores = {60, 65, 76}},
{name = "Ana", scores = {80, 85, 90}},
{name = "Leo", scores = {70, 76, 82}}
}
table.sort(students, function(a, b) return a.name < b.name end)
print("Gradebook")
local totalAvg = 0
for i, student in ipairs(students) do
local avg = average(student.scores)
totalAvg = totalAvg + avg
print(string.format("%s: %.1f (%s)", student.name, avg, grade(avg)))
end
print(string.format("Class average: %.2f", totalAvg / #students))Key points
- Students: each student is a table holding a name and a table of three scores, and all four students sit in one outer table.
- Average: the average function adds the scores with ipairs and divides the total by the score count.
- Grade: the grade function returns "A" for 90 or more, "B" for 80 or more, "C" for 70 or more, and "D" below that.
- Sort: table.sort with a small function that compares a.name < b.name puts the students in name order.
- Row: string.format builds one report line with the name, the average to one decimal place, and the grade.
- Footer: the class average is the average of the four student averages, printed with two decimal places.
In this example, average and grade are defined first, and the students table lists Mia, Sam, Ana, and Leo out of name order. table.sort then orders the students by name, the loop prints one formatted line per student with the average and grade, and the last line shows the class average of the four averages, 79.75.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A student has an average of exactly 80. Which letter does the grade function return?