0

I would like to define a command using Lua that will start and end a \savebox depending on if it is starred or not. Let's call this command \switchcolumn.

Here is the code (the first \switchcolumn that starts the box is substituted with the literal text, since it is irrelevant to the question):

\documentclass[11pt, paper = B5]{scrbook}
\usepackage{fontspec}
\usepackage{luacode}
\usepackage{xparse}

\setmainfont{Libertinus Serif}

\begin{luacode}
    dofile(kpse.find_file("mwe.lua"))
\end{luacode}

\NewDocumentCommand{\switchcolumn}{}{\directlua{SwitchColumn()}}

\begin{document}

\newsavebox{\aaa}
\savebox{\aaa}[0.5\textwidth] {
Hello World!
\switchcolumn

\end{document}

mwe.lua:

function SwitchColumn()
    tex.cprint(2, "}")
end

It doesn't work. The closing curly bracket doesn't end up in the TeX's engine input:

Runaway argument?
{ Hello World! \switchcolumn \par \end {document} 
! File ended while scanning use of \@isavebox.

I tried tex.print, tex.sprint, it's all the same.

How to set things right?

2
  • it isn't that clear what you want to do. Your Lua is never called at all as tex is scanning for the end of the argument and will hit the end of file looking for the }. tex macros are not expanded while scanning for arguments. Jul 14, 2021 at 9:03
  • perhaps you would be better to use lrbox environment rather than\savebox and then write out \end{lrbox} (although you would not need Lua for that) Jul 14, 2021 at 9:05

1 Answer 1

4

The exact Lua form of your function disn't matter as macros and commands are not executed while TeX is scanning for arguments, so the end of file is reached looking for a closing } and \switchcolumn is never expanded.

You could use the environment form lrbox but that doesn't have a width argument so I re-use the box in \makebox to set the width.

enter image description here

Lua (although you could use a tex definition here more easily)

function SwitchColumn()
tex.print('\\end{lrbox}')
end

tex

\documentclass[11pt, paper = B5]{scrbook}
\usepackage{fontspec}
\usepackage{luacode}
\usepackage{xparse}

\setmainfont{Libertinus Serif}

% over complicated:
%\begin{luacode}
%    dofile(kpse.find_file("mwe.lua"))
%\end{luacode}
\directlua{require 'mwe'}

\NewDocumentCommand{\switchcolumn}{}{\directlua{SwitchColumn()}}

\begin{document}

\newsavebox{\aaa}
\begin{lrbox}{\aaa}
Hello World!
\switchcolumn


X\makebox[0.5\textwidth]{\unhbox\aaa}X
\end{document}
1
  • "although you could use a tex definition here more easily" — obviously I want to do something more, than the mwe shows. Also I can debug Lua in a real debugger, with breakpoints and everything. TeX programming is only for real Jedi. I am an ordinary guy.
    – facetus
    Jul 14, 2021 at 10:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .