Lua Project Layout
A project layout is a folder plan that keeps modules, data, and the entry point in separate places. It makes a growing program easy to find your way around.
A path pattern points at project modules
The pattern is added to the front of package.path. Its text then leads the search path.
package.path = "mods/?.lua;" .. package.path
print(package.path:sub(1, 10))A module file is written, then used
The block writes its own module file first. Then it asks for that module by name.
local f = io.open("greet.lua", "w")
f:write("local m = {}\n")
f:write("function m.hello() return \"hi from greet\" end\n")
f:write("return m\n")
f:close()
package.path = "./?.lua;" .. package.path
local greet = require "greet"
print(greet.hello())The main file combines two modules
Two small modules each do one job. The main file joins their results into one line.
local f = io.open("calc.lua", "w")
f:write("local m = {}\n")
f:write("function m.add(a, b) return a + b end\n")
f:write("return m\n")
f:close()
local g = io.open("greet.lua", "w")
g:write("local m = {}\n")
g:write("function m.hello() return \"hi\" end\n")
g:write("return m\n")
g:close()
package.path = "./?.lua;" .. package.path
local calc = require "calc"
local greet = require "greet"
print(greet.hello() .. " " .. calc.add(4, 2))Example
local f = io.open("calc.lua", "w")
f:write("local m = {}\n")
f:write("function m.add(a, b) return a + b end\n")
f:write("function m.mul(a, b) return a * b end\n")
f:write("return m\n")
f:close()
local g = io.open("format.lua", "w")
g:write("local m = {}\n")
g:write("function m.label(v) return \"total: \" .. v end\n")
g:write("return m\n")
g:close()
package.path = "./?.lua;" .. package.path
local calc = require "calc"
local format = require "format"
print(format.label(calc.add(9, 3)))
print(format.label(calc.mul(4, 5)))Key points
- Modules folder: modules live in their own folder, apart from the entry point.
- Entry point: one main file starts the program and uses the modules.
- Path pattern: package.path gains a project-local pattern so modules are found.
- Module file: each module file returns a table of its functions.
- Main flow: the main file asks for modules, then runs the program steps.
In this example, the block writes two module files, one for arithmetic and one for labels. The main part asks for both modules. It then prints a labelled sum and a labelled product.
Note
a module file is only useful when the path pattern can reach it.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
In a sane project layout, which file starts the program?