module

Name

module – helper function for defining Knights modules

Synopsis

module(...)

Description

Placing module(...) at the top of a module's init.lua file makes some changes to the Lua environment (_ENV) in order to simplify the creation of Lua modules.

Basically, if module(...) is used, then then there is no need to explicitly return a value from your init.lua chunk. Instead, all global variables created by your init.lua (or other Lua files loaded from it using dofile) are automatically collected up and placed into a table. That table automatically becomes the return value from init.lua without you having to do anything.

Return Value

None.

Errors

If used correctly then module(...) should not raise an error.

If you get the error 'module': first argument must be module name, this means you have called the module function incorrectly (e.g. you have called it as module() instead of module(...), or called it from the wrong place).

Notes

Whether to use module(...) or not is a matter of personal preference. Some people prefer the convenience that module(...) provides, while others prefer the more explicit, "no magic" coding style that results when module(...) is avoided.

Examples

Without module(...), we could write the init.lua code for a very simple Lua module this way:

local M = {}

M.fun1 = function() print("Hello") end
M.fun2 = function() print("Goodbye") end

return M

This "module" just contains two functions that print different messages. (Think of it as representing a "utility" module that might be used by other modules.)

With module(...), the same effect could be achieved like this:

module(...)

function fun1()
    print("Hello")
end

function fun2()
    print("Goodbye")
end

Notice, in this case, there is no need to create the M table or use return M at the end of the code. Instead, all global functions created (i.e. fun1 and fun2 in this example) are automatically "exported" from the module.

In both cases, another module could "import" this module and use its functions like this:

local M = require("message_funcs")  -- Assume the above module is called "message_funcs"

M.fun1()   -- prints "Hello"
M.fun2()   -- prints "Goodbye"

See Also

require

use_strict