3

As shown in the code below, in order to use the result of \testSet{a=400, b=900}, I have to declare a global variable \g_test_result_fp and define a \testGet command. Can I directly use \fpeval{\testSet{a=400, b=900} + pi}, or in other words, is it possible to create an expandable key-value command?

\documentclass{article}

\ExplSyntaxOn


\fp_new:N \l_test_a_fp 
\fp_new:N \l_test_b_fp 
\fp_new:N \g_test_result_fp

\keys_define:nn { test }
{
  a .fp_set:N = \l_test_a_fp,
  b .fp_set:N = \l_test_b_fp,
}

\NewDocumentCommand { \testSet } { m }
{
  \keys_set:nn { test } {#1}
  \fp_gset:Nn \g_test_result_fp { \l_test_a_fp + \l_test_b_fp }
}

\NewExpandableDocumentCommand { \testGet } { }
{
  \fp_use:N \g_test_result_fp
}

\ExplSyntaxOff
\begin{document}

\testSet{a=400, b=900}
\testGet

\fpeval{\testGet + pi}

%\fpeval{\testSet{a=400, b=900} + pi}

\end{document}
3
  • 2
    \keys_define:nn is protected so there is nothing you can do here to make \testSet expandable if it uses that function. Commented 18 hours ago
  • @cfr Okay, I understand. Commented 18 hours ago
  • 1
    I meant \keys_set:nn. by 'nothing', I mean 'nothing the latex people would approve'. you could doubtless do something of which they would not approve, but it would have to rely on implementation details, in which case it would be better to use something other than l3keys. Commented 17 hours ago

2 Answers 2

5

Using expkv-cs you can define this straight forward. Notice however that if you need any assignments you can't get this to work outside of LuaTeX. expkv-cs itself doesn't need any assignments in the macros it creates.

\documentclass{article}

\usepackage{expkv-cs}
\ekvcSplit\testSet
  { % default values if you omit the key during usage
     a=400 % #1
    ,b=900 % #2
  }
  {\fpeval{#1+#2}}

\begin{document}

\fpeval{\testSet{b=20} + pi}

\end{document}

enter image description here

1
  • Thanks so much for the help. Commented 7 hours ago
6

In LuaTeX, we can use \immediateassigned primitive in order to do definitions at expand processor level.

For example, in OpTeX:

\mathinexpr
\def\testSet#1{%
   \immediateassigned{\readkv{#1}}% reading parameters at expand procesor level
   (\kv{a}+\kv{b})%               % using parameters
}

%% Test:

\expr[7]{\testSet{a=400, b=900} + pi} % expands to 1303.1415927

\bye
1
  • thank you so much for your answer. Commented 12 hours ago

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.