Just a variation on Scott H.'s solution, for showing a perhaps better way to deal with the problem.
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand{\variation}{ s O{;} m m }
{
\IfBooleanTF{#1}
{
\geoff_variation_check:nnn { #2 } { #3 } { #4 }
}
{
\geoff_variation_nocheck:nnn { #2 } { #3 } { #4 }
}
}
\msg_new:nnn { variation }
{ index~out~of~bounds }
{ You~have~requested~an~item~that~doesn't~exist }
\seq_new:N \l__geoff_item_list_seq
\cs_new_protected:Npn \geoff_variation_nocheck:nnn #1 #2 #3
{
\seq_set_split:Nnn \l__geoff_item_list_seq { #1 } { #3 }
\seq_item:Nn \l__geoff_item_list_seq { #2 }
}
\cs_new_protected:Npn \geoff_variation_check:nnn #1 #2 #3
{
\seq_set_split:Nnn \l__geoff_item_list_seq { #1 } { #3 }
\int_compare:nTF { #2 > \seq_count:N \l__geoff_item_list_seq }
{ \msg_warning:nn { variation }{ index~out~of~bounds } }
{ \seq_item:Nn \l__geoff_item_list_seq {#2} }
}
\ExplSyntaxOff
\begin{document}
\variation{3}{aaa;bbb;ccc;ddd;eee}
\variation[,]{3}{aaa,bbb,ccc,ddd,eee}
\variation{1}{aaa}
\variation{2}{aaa}
\variation*{2}{aaa}
\end{document}
The \NewDocumentCommand
instruction should be used to pass the arguments to an "internal" function. In order to better show how, I introduce a *-variant, so the control is passed either to \geoff_variation_check:nnn
or to \geoff_variation_nocheck:nnn
. The internal functions should be protected
, since they do unexpandable actions (\set...
).
The bulk of the action is splitting the argument into a sequence and returning the needed sequence item:
\seq_set_split:Nnn <sequence> { <tokens> } { <token list> }
\seq_item:Nn <sequence> { <integer expression> }