module

Creates a Lua module

Prototype

module (name, ยทยทยท)

Description

Creates a module. This is intended for use with external "package" files, however it can be used internally as shown in the example below. The module effectively has its own global variable space (because module does a setfenv) so that any functions or variables used in the module are local to the module name (for example, foo.add in the example below).

If there is a table in package.loaded[name], this table is the module. Thus, if the module has already been requested (by a require statement) another new table is not created.

Otherwise, if there is a global table t with the given name, this table is the module.

Otherwise creates a new table t and sets it as the value of the global name and the value of package.loaded[name].

This function also initializes t._NAME with the given name, t._M with the module (t itself), and t._PACKAGE with the package name (the full module name minus last component).

Finally, module sets t as the new environment of the current function and the new value of package.loaded[name], so that require returns t.

The example below shows the creation of the module "foo". In practice you would probably put the contents of the "test" function into a separate file, and then: require "test"

The nice thing about this approach is that nothing inside the module will "pollute" the global namespace, excepting the module name itself (foo in this case). Internally inside the module functions can call each other without having to use the package name (eg. add could call subtract without using foo.subtract).

You can make a "private" function inside the "foo" package by simply putting "local" in front of the function name.

function test ()
  local print = print  --> we need access to this global variable
  
  module "foo"  --> create the module now
  
  function add (a, b)
    return a + b
  end -- add
  
  function subtract (a, b)
    return a - b
  end -- subtract

  function hello (s)
    print ("hello", s)
  end -- hello

end -- function test

test ()  -- install module

foo.hello ("world")   --> hello	world
print (foo.add (2, 3))  --> 5
print (foo.subtract (7, 8))  --> -1

print (package.loaded["foo"]) --> table: 003055F0
print (foo)  --> table: 003055F0

for k, v in pairs (foo) do
  print (k, v)
end -- for 

-->

_M	table: 003055F0
_NAME	foo
_PACKAGE	

hello	function: 00305810
subtract	function: 00305760
add	function: 00305780
After the module has been created, we can see that:

foo._M is foo itself (ie. the module)
foo._NAME is "foo"
foo._PACKAGE is an empty string (if the module was "foo.bar" then _PACKAGE would be "foo.")

Lua functions

Topics