当我希望使用指令输出文本文件时,我遇到了一个问题\directlua
。在我希望换行符出现的地方,我遇到了 TeX 问题。我的解决方案是调用dofile
函数来获取从外部 Lua 脚本调用的字符串myNLChar
。此字符串可以写入输出文件,它将是一个真正的换行符。
文件wrnl2of.lua
:
myNLChar = "\n"
文件wrnl2of.tex
:
This Lua\TeX\ document does not typeset anything
interesting. It outputs a three-line text file
which contains newline characters.\par
\directlua0{
local myOutFile = "\jobname.txt"
local myLuaScript = "\jobname.lua"
dofile (myLuaScript)
derDateiname = io.open (myOutFile, "w")
derDateiname:write ("Alaska" .. myNLChar)
derDateiname:write ("California" .. myNLChar)
derDateiname:write ("Nebraska" .. myNLChar)
derDateiname:close ()
}
虽然这个策略效果不错,但我怀疑这个问题还有几种更优雅的解决方案。我渴望听到一些建议。
答案1
我在这里只用\string
一个简单的例子
This Lua\TeX\ document does not typeset anything
interesting. It outputs a three-line text file
which contains newline characters.\par
\directlua{
local myOutFile = "\jobname.txt"
local myNLChar = "\string\n"
derDateiname = io.open (myOutFile, "w")
derDateiname:write ("Alaska" .. myNLChar)
derDateiname:write ("California" .. myNLChar)
derDateiname:write ("Nebraska" .. myNLChar)
derDateiname:close ()
}
\bye
您还可以更改\catcode
反斜杠:
This Lua\TeX\ document does not typeset anything
interesting. It outputs a three-line text file
which contains newline characters.\par
\begingroup
\long\def\firstofone#1{#1}
\catcode`\/=0 %
\catcode`/\=12 %
/firstofone{%
/endgroup
/directlua{
local myOutFile = "/jobname.txt"
local myNLChar = "\n"
derDateiname = io.open (myOutFile, "w")
derDateiname:write ("Alaska" .. myNLChar)
derDateiname:write ("California" .. myNLChar)
derDateiname:write ("Nebraska" .. myNLChar)
derDateiname:close ()
}%
}
\bye
对于任何长度的 Lua 代码,最好还是用dofile()
或require()
来代替。例如,
\begin{filecontents*}{\jobname.lua}
function derDateiname(myOutFile)
local derDateiname = io.open(myOutFile, "w")
derDateiname:write("Alaska" .. "\n")
derDateiname:write("California" .. "\n")
derDateiname:write("Nebraska" .. "\n")
derDateiname:close()
end
\end{filecontents*}
\documentclass{article}
\begin{document}
This Lua\TeX\ document does not typeset anything
interesting. It outputs a three-line text file
which contains newline characters.\par
\directlua{
require("\jobname.lua")
derDateiname("\jobname")
}
\end{document}