First-Class Functions in Lua

If you’ve come this far in this book, you know that saying functions are first-class just implies there’s nothing special about them, so they can be treated like any other value. And you know that a higher-order function does at least one of two things: it either takes other functions as arguments, or it returns functions. These are important capabilities in functional languages, so let’s see how they are implemented in Lua.

Suppose we have a handy list of cats. We can use Lua’s table concept—a Swiss Army--style collection that behaves like both an array and a hash:

 local cats = {
  { name = "meg", breed = "persian" },
  { name = "mog", breed = "siamese" }
 }

A function that collects the names of all of our ...

Get Functional Programming: A PragPub Anthology now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.