typestar

Modules in Lua

A module is a table a file returns; require caches it.

-- A module is just a table a file returns; here built inline.
local inventory = (function()
  local M = {}
  local items = {}

  function M.add(name)
    items[#items + 1] = name
  end

  function M.list()
    return table.concat(items, ", ")
  end

  return M
end)()

inventory.add("rope")
inventory.add("lodestone")
print("Carrying: " .. inventory.list())

How it works

  1. The pattern: build a local M, add functions, return it.
  2. Private state (items) hides in the closure.
  3. Callers see only what M exposes.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
336
Tokens
78
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 72 seconds.

Type this snippet

Step 2 of 2 in The library, step 24 of 27 in Language basics.

← Previous Next →

Modules in other languages