Learn Lua · Tables · Lesson 3 of 5

Looping over tables

ipairs walks a list in order, giving each position and value:

LUA
local total = 0
for _, line in ipairs({ { qty = 2 }, { qty = 3 } }) do
  total = total + line.qty
end
total  --> 5

pairs walks every field of a record. Its order is fixed, but it isn't alphabetical, so use ipairs when order matters. Write _ for a value you don't need.

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 = {
  lines = {
    { product = "Flyer", quantity = 100, price = 0.5 },
    { product = "Card", quantity = 20, price = 2 },
  },
}

Steps

  1. Return total: the order's value, each line's quantity times its price, added up.
  2. Add products: a list of the product names, in order.
  3. Add largest: the product with the highest quantity.
Show a hint

Keep the largest quantity seen so far in a variable, and update largest when a line beats it.