tl;dr require is cached, dofile isn't.
In contrast to dofile, require caches which files have been requested already. For example, if you load a module example
local example = require("example")
Lua will add the handle that was returned from example to an internal table called package.loaded. If your application calls require("example") again, Lua will not load the example module again, but simply return the handle which was cached in package.loaded.
This approach also shows why it is a bad idea to define global variables in a file which is supposed to be used as a module. The luatest module from your question just defines the global name fact but does not return a handle. Therefore the Lua interpreter can't cache it and if something redefines the global name fact there is no way to get the original back. Another issue with global names is, that they tend to collide. Imagine you had a second module which also defined the fact global name. Which one is Lua supposed to take?
In principle you could use dofile for files which you strictly only load once and where all the names defined within are unlikely to collide. Personally, I prefer modules even for this situation because it reduces interdependencies and makes things reusable in other contexts.
You should restructure your example:
luatest.lua
local function fact(n)
if n == 0 then
return 1
else
return n * fact(n-1)
end
end
return { fact = fact }
test.tex
\documentclass{article}
\directlua{luatest = require("luatest")}
\newcommand*{\myluafact}[1]{%
\directlua{tex.write(luatest.fact(#1))}%
}
\begin{document}
test \myluafact{5}
\end{document}
requireis cached,dofileisn't. Therefore you are guaranteed to always get the same handle of a module fromrequire. – Henri Menke Dec 10 '18 at 05:24requirewill look into the "standard search path" instead of just the current directory, so e.g. if you put Lua files in texmf/commonstuff thenrequirecan find them butdofilecannot. Refer to luatex - LuaLatex package: \dofile results in error "no such file or directory" - TeX - LaTeX Stack Exchange – user202729 Nov 25 '22 at 11:44