在回忆录类文档中通过 \directlua 写入文件时出现问题

在回忆录类文档中通过 \directlua 写入文件时出现问题

下面是一些代码的最小示例,其中回忆录类似乎与在\directlua命令中执行的写入外部文件的 Lua 代码发生冲突。

有人能帮我找出问题的根源吗?是否有可能在不放弃回忆录课程的情况下找到解决方案?对于这个项目,我投入了大量精力。

观察到的行为:

下面有两个文件,somedocument.texsomeprogram.lua,第二个文件由第一个文件调用。

按原样运行lualatex somedocument.tex会在 luaotfload 中引发以下错误:

(/usr/local/texlive/2020/texmf-dist/tex/latex/base/ts1cmr.fd)...xmf-dist/tex/lu
atex/luaotfload/fontloader-2020-12-30.lua:19085: attempt to call a nil value (f
ield 'suffix').
<to be read again> 
relax 
l.16 \end{document}
                 
? 
! Font \TU/lmr/m/sl/10=[lmromanslant10-regular]:+tlig; at 10pt not loadable: me
tric data not found or bad.

\end(document)请注意,错误直到处理后才会出现。

我发现我可以通过以下两个更改之一(或两者)使错误消失,并且一切运行正常:

  • 在 LaTeX 序言中将回忆录类更改为文章类
  • 注释掉 Lua 代码中的三行文件 i/o 代码,这样它就不会向外部文件写入任何内容

因此,似乎是回忆录类的结合和 Lua 文件 i/o 的使用把事情搞乱了。

我最初运行的是通过 Ubuntu 存储库安装的 texlive-2019,但安装 texlive-2020 并不能解决问题。

一些背景信息:这是我第一次尝试在 LaTeX 中使用 Lua 扩展。我的 LaTeX 文档包含许多格式为 的命令,\mycommand{xxx}其中xxx既应打印在生成的文档中,又应写入外部文件。以前我使用 来从 LaTeX 执行此操作\index,但我认为使用 Lua 会有所改进。

另一个线索是这个感觉类似的问题:lualatex 的微类型错误:“尝试调用字段警告为零值”

% somedocument.tex

\documentclass{memoir}
%\documentclass{article}

\directlua{dofile("someprogram.lua")}  % someprogram.lua contains lua function somecommand
\newcommand{\luacommand}[1]{\directlua{tex.write(somecommand("#1"))}}

\begin{document}

Hello world, this is the LaTeX file. Now we will call some Lua code.

\luacommand{foo}
\luacommand{bar}

\end{document}
-- someprogram.lua
function somecommand(mystring)
    tex.print("Writing " .. mystring .. " to file")
    file = io.open("output-file.txt", "a")
    file:write(mystring .. "\n")
    file:close()
end

答案1

您正在将其声明file为全局变量。这会覆盖filelualibs 的一部分并在 luaotfload 中使用的库,因此每次加载字体的尝试都会失败。观察到它仍然适用于 article 类,这主要是运气:写入文件后使用的所有字体都已使用过,因此它们不再需要初始化,因此不会尝试访问被覆盖的库。要解决此问题,只需使用另一个名称和/或将变量设为本地变量:

-- someprogram.lua
function somecommand(mystring)
    tex.print("Writing " .. mystring .. " to file")
    local file = io.open("output-file.txt", "a")
    file:write(mystring .. "\n")
    file:close()
end

相关内容