I am trying to use a Lua script to generate LaTeX commands. Here is a minimal lua script:
my_array = {
cmdone = {1, 2},
cmdtwo = {2, 3}
}
cmd_template = "\\newcommand*{\\%s}{number one: %s, number two: %s}"
function mkcommands()
for k, v in pairs(my_array) do
-- print(string.format(cmd_template, k, v[1], v[2]))
tex.print(string.format(cmd_template, k, v[1], v[2]))
end
end
And here is the TeX file:
\documentclass[12pt]{article}
\usepackage{luacode}
\begin{luacode}
dofile("test.lua")
mkcommands()
\end{luacode}
%\newcommand*{\cmdtwo}{number one: 2, number two: 3}
%\newcommand*{\cmdone}{number one: 1, number two: 2}
\begin{document}
\cmdone
\cmdtwo
\end{document}
When I run lualatex test.tex, I get Undefined control sequence l. 15 \cmdone.
What am I doing wrong? Can this even be done?
I used the commented "print" command in the lua code to show that what was being generated looked correct. I then pasted the generated \newcommand commands into the TeX file to verify that they were working--producing the expected output
number one: 1, number two: 2 number one: 2, number two: 3
But it seems the print() and tex.print commands are producing different output.
It turns out that my problem was scope. When I used Lua to generate
\newcommandcommands inside a\begin{luacode} ... \end{luacode}environment, those commands disappeared when the environment ended. The fix was to use\directluainstead of the environment. With the same Lua file, this TeX file works: