4. Modules
1. Modules
----------------------------------------------------
-- 4. Modules.
----------------------------------------------------
-- Suppose the file mod.lua looks like this:
--[[
local m = {}
local function sayMyName()
print("Hrunkner")
end
function m.sayHello()
print("Why hello there")
sayMyName()
end
return m
--]]
-- Another file can use mod.lua's functionality:
local mod = require("mod") -- Run the file mod.lua.
-- require is the standard way to include modules.
-- require acts like: (if not cached; see below)
--[[
local mod = (function ()
<contents of mod.lua>
end)()
--]]
-- It's like mod.lua is a function body, so that
-- locals inside mod.lua are invisible outside it.
-- This works because mod here = m in mod.lua:
mod.sayHello() -- Prints: Why hello there Hrunkner
-- This is wrong; sayMyName only exists in mod.lua:
mod.sayMyName() -- error
-- require's return values are cached so a file is
-- run at most once, even when require'd many times.
-- Suppose mod2.lua contains "print('Hi!')".
local a = require("mod2") -- Prints Hi!
local b = require("mod2") -- Doesn't print; a=b.
-- dofile is like require without caching:
dofile("mod2.lua") --> Hi!
dofile("mod2.lua") --> Hi! (runs it again)
-- loadfile loads a lua file but doesn't run it yet.
F = loadfile("mod2.lua") -- Call F() to run it.
-- load is loadfile for strings.
-- (loadstring is deprecated, use load instead)
G = load("print(343)") -- Returns a function.
G() -- Prints out 343; nothing printed before now.
References