- what are modules?
- related pages: the toplevel, merge namespaces, include files
what are modules?
Some terms:
- code - this is Nelua in a string, probably from a file. You can run it for some effect.
- library - this is code that is intended to be used by other Nelua code. A likely use is for it to be
require()'d for effect (creating, modifying global state) or to return a module, or both. - module - this is a Nelua
@record{}used as a namespace of definitions - functions, variables - intended for use by other Nelua code.
Your libraries can be useful without packing them into a namespace, but namespaces offer a lot of advantages - most especially to readability, for example of string.sub():
- this function is about strings, and not submarines or subroutines
- I can find more about this function in the 'string' library documentation
- this function can have a short name like "sub" without risk of conflicting with any names in the code using it
Example of some code and its use:
print 'hello, world!'
$ nelua code.nelua hello, world!
and of a library:
require 'string'
global function greet(who: string)
print('hello, ' .. who)
end$ nelua -i 'require("library") greet("world")'
hello, world
and of a library returning a module:
require 'string'
local M = @record{}
function M.greet(who: string)
print('hello, ' .. who)
end
return M$ nelua -i 'local m = require("module") m.greet("world")'
hello, world
Note that if a library returns a module, it can no longer be run directly without some extra work:
$ nelua module.nelua module.nelua:9:1: error: main cannot return value of type 'type', only integral numbers can be returned return M ^~~~~~~~
What about Lua modules?
They work similarly. There's an example in Compile-time Counters.
It's annoying to rewrite all these 'local' names to return them in a module!
You can construct and return the module in its own step at the end of the file, like so:
require 'string'
local function greet(who: string)
print('hello, ' .. who)
end
local M = @record{}
global M.greet = greet
return M