🎓 A1Learner
🔍
0 of 47 lessons completed

Lua Modules

A module is a separate Lua file that returns a table of functions for other files to use. Splitting code into modules keeps a big program tidy, with each file holding one job.

require hands back the greeter table

require loads greeter.lua and returns its table. Calling hello on that table prints the greeting.

local greeter = require("greeter")
print(greeter.hello("Maya"))

Both greeter functions in one program

The same table holds hello and twice. Each call reaches a different function in the module.

local greeter = require("greeter")
print(greeter.hello("Sam"))
print(greeter.twice(21))

Two requires, one shared table

require runs twice here, and each line stores the result. Both handles give 20, which proves they share the same loaded table.

local first = require("greeter")
local second = require("greeter")
print(first.twice(10))
print(second.twice(10))

Example

local greeter = require("greeter")

print("Welcome Card")
print(greeter.hello("Leo"))
print("Your number doubled: " .. greeter.twice(7))

Key points

  • Module: a module is a second file that builds a table, fills it with functions, and returns that table.
  • Require: require("greeter") loads the file named greeter.lua and hands back the table it returns.
  • Load once: Lua loads a module only the first time it is required, and later calls hand back the same table.
  • Use: local greeter = require("greeter") stores the table, and greeter.hello calls one of its functions.
  • Dot call: a function inside the table is called through the table name, a dot, and the function name.

In this example, the first line loads the greeter module into a local table. The program then prints a card title, a greeting built by hello, and a line that shows twice turning 7 into 14.

Note

the name inside require has no .lua ending, because Lua adds the ending itself while searching.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does require("greeter") hand back to the main program?