Lua Modules

Lua modules are reusable code. The interesting thing about Lua modules is that like every other thing in the language a module is a Lua table. Today I create and use my own simple module.


Create a Module



Lua modules need to create and return a local, anonymous table. The code goes into a file. I'm going to use to use OO-style objects to create a basic shape class.

Screen Shot 2021-04-13 at 9.09.16 AM


Here, I'm creating a shape object in line 1. It needs to be declared local so that it doesn't conflict with anything in the programs that use it.
  • In lines 3-6 I set up some basic attributes (This is not a complete implementation.)
  • Lines 8-25 is the constructor.
  • Lines 27-30 create a method for the shape object.
  • Line 32 returns the shape object, which is just a Lua table.


It's really not important that you understand what the constructor does (you can review my Objects in Lua post). What is important that you understand that:
  • The returned table is marked local.
  • You return a table.


Using Modules



Using a Lua module is straight-forward. Here is an example program that uses my shape module. I've saved the module in a file called shape.lua.

Screen Shot 2021-04-13 at 9.16.36 AM


The key is line 3. The require keyword looks for a file with the name passed in. Here, I've specified the "shape" module, so require looks for a file shape.lua. Note that require doesn't actually look for the local variable returned (shape).

The anonymous function (the table I've called shape) is returned and assigned to the variable named Shape on line 3. Once this is done, I can use the table normally.

Search Path



Lua has a search path that is used to locate modules. This is like the PATH statement in Windows. The path is stored in Lua's global table _G, in a variable named package.path. NOTE: I have no idea why it's called package.path and not module.path, or vice-versa. You can print this out in your Lua program with:

print(_G.package.path)


On my Mac this results in:

Screen Shot 2021-04-13 at 9.26.46 AM

Being just a variable, you can assign whatever path you need into this string.

One thing to realize is that not only does require load the file from its location, it actually executes the file and returns the local table. Also, require will not reload the file multiple times if told to do so. require is more than just a simple import statement in other languages.

If you want to reload the same file multiple times, Lua has another command dofile, but it doesn't use the search path. The loaded file needs to be explicitly stated. For example:

Shape = dofile("./shape.lua")


That's enough for today.


This site does not track your information.