I am still trying to get my head around expandability and its effects on commands / functions.
I used \newcommand instead of \NewDocumentCommand since the latter is not expandable and I am not using protected functions but still the result of that function can not be evaluated by \num. What am I doing wrong?
\documentclass{article}
\usepackage{siunitx}
\ExplSyntaxOn
\fp_gzero_new:N \g__invoice_sum_fp
\NewDocumentCommand{\resetinvoicesum}{}
{
\fp_gzero_new:N \g__invoice_sum_fp
}
\resetinvoicesum
\NewDocumentCommand{\addtoinvoicesum}{m}
{
\fp_gadd:Nn \g__invoice_sum_fp { #1 }
}
\newcommand{\showinvoicesum}[1][default]
{
\fp_eval:n { \g__invoice_sum_fp }
}
\ExplSyntaxOff
\begin{document}
\addtoinvoicesum{12}
\showinvoicesum{}
\num{\showinvoicesum}
\end{document}
\newcommandis not expandable. In general it is not possible to robustly parse for an optional argument if it's not followed by at least one mandatory argument in an expandable way, so\showinvoicesumis not expandable. – Skillmon May 12 '23 at 16:37\NewExpandableDocumentCommand– David Carlisle May 12 '23 at 17:47\newcommand{\showinvoicesum}[1][default] { \fp_eval:n { \g__invoice_sum_fp } }– David Carlisle May 12 '23 at 17:51\fp_eval:nI'd suggest using\fp_to_decimal:N \g__invoice_sum_fp(should be faster, but I didn't test). – Skillmon May 12 '23 at 18:52\NewExpandableDocumentCommand! – mrCarnivore May 12 '23 at 19:00\NewExpandableDocumentCommanddoes not allow only optional parameters but must have a mandatory parameter at the end... – mrCarnivore May 12 '23 at 19:09[you can not do that in the general case without doing a\letassignment,\futurelet\tmp... \ifx\tmp[ ...assignments are by definition not expandable – David Carlisle May 12 '23 at 19:17\resultmacro, if you did\showinvoicesum \num{\result}your command can do non-expandable stuff and finally leave an answer in\resultwhich then expands for\num– David Carlisle May 12 '23 at 19:40\NewExpandableDocumentCommandessentially just grabs an argument and checks whether that is just[, and if so assumes an optional argument it then reads in. In your usage example this wouldn't be possible since the next token would be}and this would lead to a low-level TeX error as that can't be the next token when you grab a parameter, hence\NewExpandableDocumentCommanddoesn't allow optional arguments at the end of the argument signature to avoid such issues. – Skillmon May 12 '23 at 20:54