4

I'm looking for a way to obtain (in tex/latex - still difficult for me to determine the difference - I guess it should state latex) run-time defineable global variables to be used with the fp package.

I want to define a function, that each time it is invoked, creates such a variable, and a second function that can use and/or update the value of this variable.

typical result

\newcommand{\defvar}[1]{%
  % var#1 := 0
  \expandafter\FPset\csname var#1\endcsname{0}%
}

\newcommand{\addvar}[2]{%
  % var#1 += #2
  \expandafter\FPadd\csname var#1\endcsname{\csname \var#1\endcsname}{#2}%
}

unfortunately doesn't seem to work,... can somebody explain my mistake ?

4

You have a wrong \var in the definition of \addvar:

\documentclass{article}
\usepackage{fp}

\newcommand{\defvar}[1]{%
  % var#1 := 0
  \expandafter\FPset\csname var#1\endcsname{0}%
}

\newcommand{\addvar}[2]{%
  % var#1 += #2
  \expandafter\FPadd\csname var#1\endcsname{\csname var#1\endcsname}{#2}%
}

% added for debugging
\newcommand{\showvar}[1]{\typeout{var "#1" is \csname var#1\endcsname}}

\defvar{x}
\showvar{x}
\addvar{x}{3}
\showvar{x}

Here's the output on the terminal

var "x" is 0
( FP-ADD )
var "x" is 3.000000000000000000

A different implementation using expl3 and its fp module; I also added a convenience command \usevar.

\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\defvar}{m}
 {
  \fp_new:c { l_liselorev_var_#1_fp }
 }

\NewDocumentCommand{\addvar}{mm}
 {
  % var#1 += #2
  \fp_add:cn { l_liselorev_var_#1_fp } { #2 }
 }

\DeclareExpandableDocumentCommand{\usevar}{m}
 {
  \fp_use:c { l_liselorev_var_#1_fp }
 }

\NewDocumentCommand{\showvar}{m}
 {
  \fp_show:c { l_liselorev_var_#1_fp }
 }
\ExplSyntaxOff

\defvar{x}
\showvar{x}
\addvar{x}{3}
\showvar{x}

The output on the terminal:

> 0.
<recently read> }

l.28 \showvar{x}

? 
> 3.
<recently read> }

l.30 \showvar{x}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.