I have a Lua function that generates LaTeX content (a string containing LaTeX commands like "\\textbf{foo}") and it can be successfully outputted with \lua_now:n and tex.print(). Now I'm planning to record the content for the purpose of l3build regression test and I try to pass the content to a token list and then write it the log file with \tl_show:N. However the following code raises an error: Illegal parameter number in definition of \l__csl_bibliography_tl. Is there another approach?
\documentclass{article}
\usepackage{luacode}
\begin{luacode*}
function make_bibliography()
local result = "\\textbf{Foo}"
tex.print(result)
end
\end{luacode*}
\ExplSyntaxOn
\tl_new:N \l__csl_bibliography_tl
\cs_new:Npn \printbibliography
{
% \lua_now:n { make_bibliography() } % It works fine.
\tl_set:Nx \l__csl_bibliography_tl { \lua_now:n { make_bibliography() } }
\tl_show:N \l__csl_bibliography_tl
\tl_use:N \l__csl_bibliography_tl
}
\ExplSyntaxOff
\begin{document}
\printbibliography
\end{document}

token.set_macrodoes not handle the case whereresultcontains e.g. a~character and the catcode of~is currently active correctly, as well as the case where some control sequence is in the string but not in the hash table. → luatex - tilde ~ in lua adds a new line - TeX - LaTeX Stack Exchange & linked questions from there. – user202729 Sep 23 '22 at 07:05