typestar

grade_report.lua in Lua

Report cards from a table roster, an elseif ladder, and format.

-- Average each student's scores and print a letter-grade report.

local roster = {
  { name = "Ada", scores = { 92, 88, 97 } },
  { name = "Grace", scores = { 84, 91, 78 } },
  { name = "Alan", scores = { 70, 66, 74 } },
  { name = "Edsger", scores = { 58, 67, 61 } },
}

local function average(student)
  local total = 0
  for _, s in ipairs(student.scores) do total = total + s end
  return total / #student.scores
end

local function letter(avg)
  if avg >= 90 then return "A"
  elseif avg >= 80 then return "B"
  elseif avg >= 70 then return "C"
  elseif avg >= 60 then return "D"
  else return "F" end
end

table.sort(roster, function(a, b) return a.name < b.name end)

print("student  avg grade")
local class_total, class_count = 0, 0
for _, s in ipairs(roster) do
  local avg = average(s)
  print(string.format("%-8s %4.1f  %s", s.name, avg, letter(avg)))
  for _, score in ipairs(s.scores) do
    class_total = class_total + score
    class_count = class_count + 1
  end
end
print(string.format("Class average: %.1f", class_total / class_count))

How it works

  1. Each student is a table with a name and a scores array.
  2. letter grades through an if/elseif ladder.
  3. One pass accumulates the class-wide average.

Keywords and builtins used here

The run, in numbers

Lines
36
Characters to type
1014
Tokens
264
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 244 seconds.

Type this snippet

Step 2 of 3 in Encore, step 26 of 27 in Language basics.

← Previous Next →