Learn Lua · Tables · Lesson 3 of 5
Looping over tables
ipairs walks a list in order, giving each position and value:
local total = 0
for _, line in ipairs({ { qty = 2 }, { qty = 3 } }) do
total = total + line.qty
end
total --> 5pairs 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.
input = {
lines = {
{ product = "Flyer", quantity = 100, price = 0.5 },
{ product = "Card", quantity = 20, price = 2 },
},
}Steps
- Return
total: the order's value, each line'squantitytimes itsprice, added up. - Add
products: a list of the product names, in order. - 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.