Learn Lua · Functions · Lesson 3 of 3

Functions as values

A function is a value, like a number or a string. You can store it, pass it to another function, or return it. table.sort_by takes a function that picks what to sort on:

LUA
local orders = { { id = "A", total = 50 }, { id = "B", total = 150 } }
table.sort_by(orders, function(o) return -o.total end)[1].id  --> "B"

A function made inside another one remembers the values around it. This is how you build a family of similar functions:

LUA
local function makeDiscount(percent)
  return function(total) return total * (100 - percent) / 100 end
end
local tenOff = makeDiscount(10)
tenOff(200)  --> 180.0

What your code receives

Your code gets its data as input. The type Input line at the top of the code lists every field, and the editor uses it to suggest field names and spot typos. Here is an example. Each check sends different values, so work from the fields rather than these exact values.

LUA
input = {
  orders = {
    { id = "A", customer = "Cy", total = 50 },
    { id = "B", customer = "Ada", total = 150 },
  },
}

Steps

  1. Return byTotal: the order ids, largest total first.
  2. Add byName: the order ids, sorted by customer name.
  3. Add discounted: each order total with 10% off, in the original order, using a function made by makeDiscount(10).
Show a hint

Sort with table.sort_by, then table.map the result to ids. A small function that turns orders into ids saves writing that twice. For step 3, make tenOff once with makeDiscount(10), then call it on each order's total.