The Wayback Machine - https://web.archive.org/web/20210508223105/https://lua-users.org/wiki/ModuleDefinition

Module Definition

lua-users home
wiki

There are many ways to define a "module" [1] in Lua.
See More

From a Table

-- mymodule.lua
local M = {} -- public interface

-- private
local x = 1
local function baz() print 'test' end

function M.foo() print("foo", x) end

function M.bar()
  M.foo()
  baz()
  print "bar"
end

return M

-- Example usage:
local MM = require 'mymodule'
MM.bar()

This is a common approach. It is simple, relies on no external code, avoids globals, and has few pitfalls. Externally facing variables are prefixed by "M." and clearly seen.

See Also


RecentChanges · preferences
edit · history
Last edited February 19, 2015 5:01 pm GMT (diff)