🎓 A1Learner
🔍
0 of 52 lessons completed

Lua Module Patterns

A module pattern is a way to group related functions in one table and return that table from a chunk. Only the functions placed in the table are visible to code outside the chunk.

A module is a table returned from a chunk

The chunk builds a table with one function. The returned table is the module.

local greet = (function()
  local M = {}
  function M.hello(name)
    return "hello, " .. name
  end
  return M
end)()
print(greet.hello("Ana"))

A helper left out of the table stays private

The public function uses a local helper. Outside code cannot see that helper on the table.

local calc = (function()
  local M = {}
  local function double(n)
    return n * 2
  end
  function M.quad(n)
    return double(double(n))
  end
  return M
end)()
print(calc.quad(3))
print(calc.double)

One module uses another module's table

The second chunk receives the first module as an argument. It calls the first module's function inside its own function.

local mathx = (function()
  local M = {}
  function M.triple(n)
    return n * 3
  end
  return M
end)()
local app = (function(dep)
  local M = {}
  function M.addTriple(a, b)
    return dep.triple(a) + dep.triple(b)
  end
  return M
end)(mathx)
print(app.addTriple(2, 3))

Example

local store = (function()
  local M = {}
  local prices = {apple = 2, bread = 3}
  function M.price(item)
    return prices[item]
  end
  return M
end)()
local cart = (function(shop)
  local M = {}
  function M.bill(a, b)
    return shop.price(a) + shop.price(b)
  end
  return M
end)(store)
print(cart.bill("apple", "bread"))
print(store.prices)

Key points

  • Returned table: a chunk builds a table, adds functions to it, and returns it as the module.
  • Private helper: a local function defined inside the chunk but left out of the table stays private.
  • Public function: a function stored in the returned table can be called from outside the chunk.
  • State privacy: a local variable inside the chunk is visible only to functions defined in that chunk.
  • Using another module: one module can receive another module's table and call its functions.

In this example, the store module keeps its prices table private and exposes only a price function. The cart module receives the store table, adds the price of an apple and a loaf of bread, and the final nil proves the prices table is not visible outside the store.

Note

at this level a module is built in the same file, so no file outside the file is loaded.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

A module keeps a helper local and leaves it out of the returned table. What does outside code get when it reads module.helper?