Modules in Lua
A module is a table a file returns; require caches it.
-- A module is just a table a file returns; here built inline.
local inventory = (function()
local M = {}
local items = {}
function M.add(name)
items[#items + 1] = name
end
function M.list()
return table.concat(items, ", ")
end
return M
end)()
inventory.add("rope")
inventory.add("lodestone")
print("Carrying: " .. inventory.list())
How it works
- The pattern: build a local
M, add functions, return it. - Private state (
items) hides in the closure. - Callers see only what
Mexposes.
Keywords and builtins used here
Maddendfunctionlistlocalprintreturn
The run, in numbers
- Lines
- 19
- Characters to type
- 336
- Tokens
- 78
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 72 seconds.
Step 2 of 2 in The library, step 24 of 27 in Language basics.