I write a document class and want to execute something a certain number of times, depending on a user-defined quantity. So I thought I'd use a foreach
loop from PGF together with accessor macros:
\documentclass{scrartcl}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{xparse,etoolbox,pgffor}
\makeatletter
\csdef{my@test}{3}
\DeclareDocumentCommand{\val}{m g}{%
\csname #1@#2\endcsname%
}
\makeatother
\begin{document}
Testing direct: \csname my@test\endcsname
Testing macro: \val{my}{test}
\foreach \i in {1,...,\csname my@test\endcsname}{a}
\foreach \i in {1,...,\val{my}{test}}{a}
\end{document}
Unfortunately, using val
breaks foreach
:
with error message Illegal unit of measure (pt inserted)
(several times).
Funny: if I use parameter specification {m m}
instead of {m g}
, the problem goes away.
It is feasible to not use the macro inside the class definition -- I do need the optional parameter, though -- but what is going on here?
Background
Users can create a list of X
s by using a macro of the form
\addX{group}{name}{key1=val1,key2=val2,..}
This macro is implemented with xparse
and keyval
. It stores the information in macros of the form \X@group@name@key
. In order to hide this from users, I provide accessor macros like val
above. There are also macros and environments that utilise the created list directly, one of which would contain a loop as defined above, repeating stuff (for every X
) depending on user-provided values.
The last parameter of val
is to be optional so that a default value can be returned if the user provides no key (which would be the value I suppose will be requested most often).
\foreach\i in {1,...,\val{my}{test}}{...}
? I don't think so. – egreg Nov 9 '13 at 14:53\val
in other contexts. If possible, I'd like both usage cases to work for my and their convenience; if that's not possible, I'll choose theirs. – Raphael Nov 9 '13 at 14:54