I am trying to write the contents of \foo
to a file using LuaLatex.
Consider the following example:
\newcommand{\abcd}{test}
\newcommand{\foo}{XXX \abcd}
\directlua{
local f = {}
f.foo = token.get_macro 'foo'
(...)
When writing the contents of f.foo
to a file later, the content will contain the string XXX \\abcd
.
If instead we change this to the following:
f.foo = "\luaescapestring{\foo}"
The result will be the intended XXX test
.
When the command \foo
contains 'special' commands like ~
, the result will be XXX \\protect \\unhbox \\voidb@x \\penalty \\@M \\ {} test
. Now this is ugly, but can be parsed/is workable. However, when commands like \\
or \xspace
are used, the compilation will fail, such as:
! Undefined control sequence.
\GenericError ...
#4 \errhelp \@err@ ...
l.180 }
The error message seems to differ based on the command that was used.
Is there a way to expand the command \foo
such that recursive expansion is performed and arbitrary special commands are protected/escaped or at the least compilation does not break?
EDIT 1
File main.tex
:
\documentclass[british]{report}
\usepackage{luacode}
\begin{document}
Test text
\newcommand{\abcd}{test}
\newcommand{\foo}{XXX \\ \abcd}
\directlua{
local f = {}
f.foo = "\luaescapestring{\foo}"
local fd = io.open("test.out", "a")
fd:write(f.foo)
fd:flush()
fd:close()
}
\end{document}
Compiled with latexmk -pdf -pdflatex="lualatex" main.tex
Above throws an error, but works with \newcommand{\foo}{XXX \abcd}
.
\protected@edef
first to expand everything as much as is safe then wrote the resulting tokens to the file.\protected@edef
. In the mean time I have added an example to the original post.\newcommand{\foo}{XXX \abcd}
I get [\di rectlua]:1: bad argument #1 to 'close' (FILE* expected, got no value) stack traceback: [C]: in field 'close' [\directlua]:1: in main chunk. l.15 }.close
not:close
as the last line of Lua.