[Tex/LaTex] Define and set length in one command

expansionlengthsmacros

Sorry this might be a very simple question, I am trying to cleanup a style file, and would like to write a command that basically runs the following code:

\newlength{<name>}\setlength{<name>}{<value>}

Based on another command that runs a \def, I though I'd be able to use expandafter and csname easily; here is what I tried:

\newcommand{\deflen}[2]{%
    \expandafter\newlength{%
    \csname #1\endcsname}\setlength{%
    \csname #1\endcsname}{#2}
}

Unfortunately, this seems to generate an error related to csname being already defined. I think it means that I can't use csname twice in the same expand, but I don't know how to define the name first, and then use it twice… Help? 🙂

Best Answer

You need to assemble the control sequence name before defining with \newcommand, and before using it. This can be achieved using \expandafter twice.

\newcommand{\deflen}[2]{%      
    \expandafter\newlength\csname #1\endcsname
    \expandafter\setlength\csname #1\endcsname{#2}%
}

\deflen{mylength}{12pt}

\showthe\mylength
Related Question