从Lua脚本输出LaTeX命令

问题描述 投票:0回答:1

我正在尝试使用 Lua 脚本生成 LaTeX 命令。这是一个最小的 lua 脚本:

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

这是 TeX 文件:

\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}

当我跑步

lualatex test.tex
时,我得到
Undefined control sequence l. 15 \cmdone

我做错了什么?这还可以吗?

我在 lua 代码中使用了带注释的“print”命令来显示生成的内容看起来是正确的。然后,我将生成的

\newcommand
命令粘贴到 TeX 文件中,以验证它们是否正在工作 - 产生预期的输出

number one: 1, number two: 2 number one: 2, number two: 3

但是

print()
tex.print
命令似乎产生不同的输出。

lua latex tex
1个回答
0
投票

事实证明我的问题是范围。当我使用 Lua 在

\newcommand
环境中生成
\begin{luacode} ... \end{luacode}
命令时,这些命令会在环境结束时消失。解决方法是使用
\directlua
而不是环境。使用相同的 Lua 文件,这个 TeX 文件可以工作:

\documentclass[12pt]{article}

\usepackage{luacode}

\directlua{dofile("test.lua")
mkcommands()}

\begin{document}

\cmdone

\cmdtwo

\end{document}
© www.soinside.com 2019 - 2024. All rights reserved.