# How can I dump Lua code to a format file?

From this format:

%% testformat.ini
\input plain
\directlua {tex.enableprimitives('', tex.extraprimitives())}
\directlua {
testFunction = function ()
tex.print("This was print by Lua's testFunction.\par")
end
}
%% \directlua {testFunction()}
%% \bye
\dump


I create a testformat.fmt with $luatex -ini testformat.ini, but when trying to use it with the following test file: %% test-testformat.tex \directlua{testFunction()} \bye  the globaly defined function testFunction is lost: $ luatex -fmt testFormat.fmt test-testformat.tex
This is LuaTeX, Version beta-0.70.1-2011120612
(./test-testformat.tex
! LuaTeX error <\directlua >:1: attempt to call global 'testFunction' (a nil va
lue)
stack traceback:
<\directlua >:1: in main chunk.
l.2 \directlua{testFunction()}

?


Should I do another trick in Lua or it simply can't be dumped and I must use something like \everyjob{\directlua{dofile("testformat.lua")}}?

For the LaTeX3 l3bootstrap module, we wanted to enable the equivalent of \pdfstrcmp using Lua code for LuaTeX. To build that into a format, we wanted to avoid having to read a .lua file each run. Taco Hoekwater suggested the use of lua.bytecode. We use this as:

\directlua
{
lua.bytecode[1] = function ()
function strcmp (A, B)
if A == B then
tex.write("0")
elseif A < B then
tex.write("-1")
else
tex.write("1")
end
end
end
lua.bytecode[1]()
}
\everyjob\expandafter
{\the\everyjob\directlua{lua.bytecode[1]()}}


i.e. you have to save the bytecode and use the \everyjob TeX primitive to active it for each run. (I've modified slightly from the version in the .dtx as there are other details there which are not relevant to this question.)

For reference, you would access the above using something like

\long\def\pdfstrcmp#1#2{%
\directlua{strcmp("\luaescapestring{#1}","\luaescapestring{#2}" )}%
}


(The pdfstrcmds package calls this \pdf@strcmp, as it requires an additional expansion compared to the primitive and so is 'safest' given a different name. In the LaTeX3 load code, that's not a worry as we don't directly expose this, so we take a slightly different approach.)

• I've answered in the absence of one from a LuaTeX expert: hopefully one will swing by sooner or later! Jun 30 '13 at 16:05
• Probably \everyjob\expandafter{\the\expandafter\everyjob\directlua{...}} so not to clobber the current value of \everyjob Jun 30 '13 at 16:07
• @egreg OK: I'm taking this from format-mode code, where I know at the point of use the status of \everyjob :-) Jun 30 '13 at 16:08
• You missed an \expandafter if you want to also expand \directlua Jun 30 '13 at 16:11
• @JosephWright: this is the correct answer. Jul 1 '13 at 8:48