Learn Lua · Functions · Lesson 2 of 3

Table helpers

CoCoCo adds helpers that save writing loops. Each takes a list and a function that works on one element. The function doesn't need a name: function(o) return o.id end is a function written right where it's used, taking one order o and giving back its id.

LUA
local orders = { { id = "A", total = 50 }, { id = "B", total = 150 } }
table.map(orders, function(o) return o.id end)                    --> {"A", "B"}
#table.filter(orders, function(o) return o.total >= 100 end)       --> 1
table.sorted({ "Cy", "Ada", "Bo" })                                --> {"Ada", "Bo", "Cy"}
table.any(orders, function(o) return o.total > 100 end)           --> true
table.size({ a = 1, b = 2 })                                       --> 2

table.any tells you whether any element passes. table.sorted returns a new sorted list and leaves the original alone. table.size counts every field, where # counts only a list's positions. In the Input line, { [string]: any } means a table with any field names, holding any values.

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 },
  },
  extra = { rush = true, gift = "wrap" },
}

Steps

  1. Return names: the customer names from input.orders, sorted alphabetically.
  2. Add big: the ids of orders with a total of 100 or more, in their original order.
  3. Add extras: how many fields input.extra has.
Show a hint

The result of one helper can go straight into another. For big, filter the orders first, then map what's left to their ids.