Skip to content

Modules

At this point you know how the most important standard libraries in Lune work and how to use them - and your code may be getting longer and more difficult to read.

Modularizing your code and splitting it across several files in Lune is different from other versions of Lua, and more similar to how things work in other languages such as JavaScript.

Let’s start with a typical module setup that we’ll use throughout this chapter:

  • main.luau
  • sibling.luau
  • Directorydirectory
    • init.luau
    • child.luau

This structure shows the two main patterns you’ll use - individual module files (sibling.luau) and directory modules (modules/ with its init.luau). The contents of these files are not very important for this article, but here is an example for the sake of completeness:

main.luau
local sibling = require("./sibling")
local directory = require("./directory")
print(sibling.Hello) --> World
print(directory.Child.Foo) --> Bar
print(directory.Child.Fizz) --> Buzz
print(directory.Sibling.Hello) --> World

Looking at our main file, you’ll notice the require paths always start with ./ or ../. This means “relative to the current file”, the same way it does in your terminal. When main.luau requires "./sibling", Lune looks for sibling.luau in the same directory as main.

The interesting part is require("./modules"). Lune sees this is a directory and automatically looks for modules/init.luau. Inside that init file, we use two different types of require statements:

The statement require("@self/child") uses the special @self alias. Since init files represent their parent directory, @self here means - inside the “modules” directory. Without it, require("./child") would look for child.luau next to the “modules” directory, not inside it.

If you’re arriving at Lune with experience in other runtimes & languages, these comparisons may help you get oriented. If you want to get right into the nitty-gritty details, feel free to skip this section completely.

Traditional Lua Structure:

  • main.lua
  • mylib.lua
  • Directoryutils/
    • init.lua
    • helper.lua
main.lua
-- Lua 5.x - requires are relative to the working directory
-- You need to configure package.path:
package.path = package.path .. ";./utils/?.lua"
local mylib = require("mylib") -- Only works if CWD is correct
local utils = require("utils") -- Needs package.path setup
local helper = require("utils.helper") -- Uses dots, not slashes
main.luau
-- Lune - requires are relative to the file
local mylib = require("./mylib") -- Always works
local utils = require("./utils") -- No path config needed
local helper = require("./utils/helper") -- Uses slashes like paths

The main difference here is that, in traditional Lua, requires depend on where you run the script from. In Lune, requires are relative to the file containing them, making your code portable and predictable.