Help with context variables and their treatment

Hello everyone, sorry for my English, I only speak Spanish.
I am new to Node-red, and I have come across this doubt.
I want to save a data in a context variable, to later recover it without modifying its saved value.
example:
In a function block I store a value obtained from a process:

flow.set("variable.data",100);code here

but if later in another block I retrieve this value and do:

msg.payload = flow.get("variable");
msg.payload.data = 200;
return msg;

the value stored in flow.variable.data (context) is also modified (it becomes 200)
I'm not understanding, shouldn't it be kept?
Is it possible that an object cannot be saved to a context variable or do I need to do it as JSON?
Sorry if it's a very stupid question.
Greetings to everybody and thanks.

Javascript stores arrays and objects by reference (google it you will get a full explanation).

So you say msg.payload = flow.get, now both context and payload point to the same memory reference.

You would need to copy/clone the value. Node-red provides RED.util.cloneMessage() for this reason
https://nodered.org/docs/api/modules/v/0.20.0/@node-red_util_util.html
e.g

msg.payload = RED.util.cloneMessage( flow.get("variable") );
2 Likes

Hello E1cid, thank you very much for your prompt response.
Now it's clear to me what's going on, I missed that detail...
If I apply the change node before the function block, does it get a "copy" of the context variable or am I wrong?
slds

The change node has an option to make a deep copy of a msg or context, as you can get the same issue when setting msg/context to another in some cases.

Ok, that's more than clear to me.
Once again, thank you very much for your help!
slds
Richard

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.