Lua Notes

nelua modules
Login
  1. what are modules?
  2. related pages: the toplevel, merge namespaces, include files

what are modules?

Some terms:

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():

  1. this function is about strings, and not submarines or subroutines
  2. I can find more about this function in the 'string' library documentation
  3. 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