Next: 8.9 A CFunction Up: 8 Some Examples Previous: 8.7 Programming with Classes

8.8 Modules

Here we explain one possible way to simulate modules in Lua. The main idea is to use a table to store the module functions.

A module should be written as a separate chunk, starting with:

if modulename then return end  -- avoid loading twice the same module
modulename = {}  -- create a table to represent the module
After that, functions can be directly defined with the syntax
function modulename.foo (...)
  ...
end

Any code that needs this module has only to execute dofile("filename") , where filename is the file where the module is written. After this, any function can be called with

modulename.foo(...)

If a module function is going to be used many times, the program can give a local name to it. Because functions are values, it is enough to write

localname = modulename.foo
Finally, a module may be opened, giving direct access to all its functions, as shown in the code below.
function open (mod)
  local n, f = next(mod, nil)
  while n do
    setglobal(n, f)
    n, f = next(mod, n)
  end
end


Next: 8.9 A CFunction Up: 8 Some Examples Previous: 8.7 Programming with Classes