Lua Functional Programming/Functions

In Lua, as in Lisp, functions are a kind of data type; you can assign them to variables and pass them around in your code.

Defining Functions
Functions can be defined in the "ordinary" way, and we can call them. We can access the function object created simply by using its name without any parentheses. Thus we can pass the function as an argument, store it in a data structure, etc. So-called lambda expressions or anonymous inline functions can also be created in Lua. They are similar to the "ordinary" functions described above in almost every way. Note that functions and other variables share the same namespace in Lua (and in most other languages), unlike Lisp. In fact, in Lua, a function is just another kind of data you can store in a variable.

Functional Arguments
Function objects can be passed to other functions as arguments. To invoke an argument as a function, just append the parenthesised list that you want to invoke it with. Using the  function defined earlier, we can do things like The "canonical" example of a function that takes another function as a parameter is. Unfortunately  does not come with Lua, so we'll have to code it ourselves. This is a simple  implementation that only works with one array. But it works well: A more complex  implementation that works with more than one array is possible: And let's use it: Sort is built-in, though, and we can pass a sorting function if we want. On Lisp provides an example of a remove-if implementation in Lisp. Remove-if is not built-in into Lua, so we might as well code a Lua implementation which is equivalent to the Lisp code below. Compare with the following Lisp code: Both the Lua and Lisp code above are tail-recursive safe (see Tail Recursion below). (Most implementations for both languages support tail-recursion optimising.) Just for comparison, here's how I would code a "pure" Lua version: In Lua, we have to define the helper functions  and   which is built-in into Lisp, but using the   is quite easy: