TransWikia.com

Can't use a macro as argument to a tabular if it's not used in the first column

TeX - LaTeX Asked by Jander on October 28, 2020

I have a more complex problem than the MWE I provide. The example, however, points directly to my issue.

I have a macro to do some processing (like specialline in the MWE) and pass it to another macro, which is responsible to produce the line of the itself (tableline).

documentclass[12pt,a4paper]{article}

newcounter{sum}
newcommand{tableline}[3]{%
    addtocounter{sum}{#3}%
    #1 & #2 & #3 
}

newcommand{specialline}[1][]{%
    defmyinput{#1}%
    ifxmyinputempty%
        defmytext{---}%
    else%
        defmytext{textit{myinput}}%
    fi%
    tableline{mytext}{}{100} %%% this works
    %tableline{}{mytext}{100} %%% this fails
}

begin{document}

begin{tabular}{ccc}
    A & B & C 
    hline
    tableline{X}{Y}{10}
    tableline{M}{L}{40}
    tableline{K}{T}{50}
    specialline
    specialline[something]
    hline
    & & thesum 
end{tabular}

end{document}

If the macro mytext goes to the first column, everything goes fine. But in any other column the compilation fails. Here’s the log:

! Undefined control sequence.
<argument> mytext 
                   
l.29        specialline
                   [something]
The control sequence at the end of the top line
of your error message was never def'ed. If you have
misspelled it (e.g., `hobx'), type `I' and the correct
spelling (e.g., `Ihbox'). Otherwise just continue,
and I'll forget about whatever was undefined.

The actual tableline and specialline I use are more complex and involves several other macros along with writing to a temporary file. So replicate part of the code of tableline in specialline is not desirable, since maintenance will suffer.

My question: why does it fails to compile and how can I overcome this problem?

One Answer

Table cells act as groups, meaning that the macros myinput and mytext are defined in the first cell of the row and exist only there. One possible solution would be to replace def by gdef but I'd rather avoid the complicated construction with helper macros and put the code directly in the second argument of tableline.

documentclass[12pt,a4paper]{article}

newcounter{sum}

newcommand{tableline}[3]{%
    addtocounter{sum}{#3}%
    #1 & #2 & #3 
}

newcommand{specialline}[1][]{%
    tableline{}{ifrelaxdetokenize{#1}relax---elsetextit{#1}fi}{100}%
}

begin{document}

begin{tabular}{ccc}
    A & B & C 
    hline
    tableline{X}{Y}{10}
    tableline{M}{L}{40}
    tableline{K}{T}{50}
    specialline
    specialline[something]
    hline
    & & thesum
end{tabular}

end{document}

enter image description here

Note that I have used a somewhat safer test for emptyness..

Correct answer by campa on October 28, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP