Lesson 14 of 15

Modules

Modules

In Lua, a module is just a table containing functions and values. The conventional pattern is:

local M = {}

function M.greet(name)
  return "Hello, " .. name
end

function M.farewell(name)
  return "Goodbye, " .. name
end

return M

You access module functions with dot notation: M.greet("Lua").

Encapsulation

Local functions inside the module file are private:

local M = {}

local function helper(x)
  return x * 2
end

function M.compute(x)
  return helper(x) + 1
end

helper is not accessible outside the module, but M.compute is.

Your Task

Create a simple math module with add and sub functions.

JS Transpiler loading...
Loading...
Click "Run" to execute your code.