# [NTG-context] passing variables/data between context and lua

Tue Oct 8 14:55:30 CEST 2019

On Tue, 8 Oct 2019, Rudolf Bahr wrote:

> On Sun, Oct 06, 2019 at 10:44:12PM +0200, Wolfgang Schuster wrote:
>
>> While it is true that you're free to choose the name for the keys there are
>> two keys with a special meaning, these two keys are "reset" and "set". The
>> value of the "reset" key is used before the values in \setvariables are
>> stored while "set" is used after the values are stored.
>
> Hello Wolfgang,
>
>
> Concerning the two keys with a special meaning, "reset" and "set", remains a question
> to me. For what are they good? Does "reset" clear a data area, namespace perhaps,
> before new data are stored there? If they are keys, what is there value or are they
> commands?

\setvariables
[dummy]
[
set={AAA},
reset={BBB},
]

\starttext
Hello World!
\setvariables[dummy][key=value]
\stoptext

When the \setvariables[dummy][key=value] is called, it first executes the
value of reset key. So the output of the above is


Hello World! BBBAAA


Now suppose you want to do some calculations based on the value
of passed key. Let's take a variation of the original question, and define
a macro where we can say

\setvariables[exam][points=5]
\setvariables[exam][points=10]

and we can a macro \totalpoints to show the number of points. (There are
probably better ways to do this than setvariables ...)

Here is one way to define it:

\def\totalpoints{0}
\setvariables
[exam]
[
points=0, % This is important.
set={\edef\totalpoints{\the\numexpr(\totalpoints + \getvariable{exam}{points})\relax}},
]

\starttext
\setvariables[exam][points=5]
\setvariables[exam][points=10]
The exam has \totalpoints\ points.
\stoptext

So, everytime \setvariables is call, the value of the set key is
executed. If I set the value of the set key to code that updates the
value of \totalpoints macro, then I get the desired behavior.

Writing macros as value of a key can be cumbersome to read. So, we can use
setups:

\def\totalpoints{0}

\startsetups updatepoints
\edef\totalpoints{\the\numexpr(\totalpoints + \getvariable{exam}{points})\relax}
\stopsetups

\setvariables
[exam]
[
points=0,
set=\directsetup{updatepoints},
]

\starttext
\setvariables[exam][points=5]
\setvariables[exam][points=10]
The exam has \totalpoints\ points.
\stoptext

That's it.