Module:Util/tables: Difference between revisions

From Zelda Wiki, the Zelda encyclopedia
Jump to navigation Jump to search
m (PhantomCaleb moved page Module:Util/Table to Module:Util/tbl without leaving a redirect)
m (PhantomCaleb moved page Module:Util/tbl to Module:Util/tables without leaving a redirect)
 
(No difference)

Latest revision as of 17:37, 5 May 2024

This is the base page for utility functions that operate on Lua tables. The functionality and naming is inspired by the Lodash JavaScript library.

Functions

Currying

Some of the functions here (and in Module:Util/strings) have a curried version that has the same name but with a _ prefix. These are used to create iteratees and are therefore useful for composing functions as shown on line 3 in this example:

Function
With UtilsWithout Utils
function gamesStartingWithThe(games)
  local titles = utils.tables.map(games, "subtitle")
  local result = utils.tables.filter(titles, utilsString._startsWith("The")) 
  return result
end
function gamesStartingWithThe(games)
  local result = {}
  for _, game in ipairs(games) do
    if string.sub(game.subtitle, 1, 3) == "The" then
      table.insert(result, game.subtitle)
    end
  end
  return result
end
gamesStartingWithThe({
  {
    code = "TWW",
    subtitle = "The Wind Waker",
  },
  {
    code = "TMC",
    subtitle = "The Minish Cap",
  },
  {
    code = "TP",
    subtitle = "Twilight Princess",
  },
})
{"The Wind Waker", "The Minish Cap"}

All of this can of course be achieved just with built-in Lua functions, as shown in the second tab above. However, code that uses the utility functions is often clearer by virtue of being declarative rather than imperative. While it does require one to be familiar with the concept of higher-order functions (specifically map and filter), which may not be a given for novices, they are concepts worth learning due to the expressiveness they provide.

Imperative vs. Declarative Code

Code is said to be declarative when it describes what the program is doing. Imperative code lays out how program works, but what the program is doing may not be immediately self-evident.

In the above example, the function is mapping an array of objects to an array of strings, then filtering those strings starting with the word "The". The version with utils states exactly that, and is therefore declarative. The version without utils is imperative because shows how it maps and filters but does not state as clearly what it is doing.