Setting Global var in a function using a variable name

I found a similar forum post of what I am trying to do, yet, for me it is not working.
I am on v4.0.9

let gname = msg.topic.split ("/")[1];

var OneZero="0";
if(msg.payload=="true") {
    OneZero="1";
}
global.set ( gname + ".State"  , OneZero );
return msg;

Injecting directly works. The function does not. I tried using "State." + gname and it did not do it either.

Help please.

I have used Claude 3.7 to generate a response -> including a test case (which I thought was quite cool)

I am not sure the rules in using AI to generate response however from my perpesctive this is an appropriate use of Claude. If it contravenes any rules feel free to delete

The answers seem sensible although the context on the global set seems out of whack however it appears to do no harm

Claude response

You will notice at the bottom it has able to create a nice test flow. From my testing it appears work. I am not keen on it returning NULL so I have changed the code to return the unchanged msg (even that is not great)

In case the link does not work and for longevity

It looks like you're working with Node-RED or a similar flow-based programming environment. There are a few potential issues that could be causing your code not to work:

  1. The most likely issue is with how you're accessing msg.topic. If msg.topic doesn't contain a "/" character or it's undefined, then split("/")[1] will return undefined.
  2. You're setting a global variable with global.set() but you might be missing a context to attach it to.

Let me help you debug this. Here's a corrected version that includes error handling:

// First, validate that msg.topic exists and has the correct format
if (!msg.topic || !msg.topic.includes("/")) {
    node.error("Invalid msg.topic: " + msg.topic);
    return msg; // Exit the function early
}

// Extract the name from the topic
let gname = msg.topic.split("/")[1];

// Check if gname is valid
if (!gname) {
    node.error("Could not extract gname from msg.topic: " + msg.topic);
    return msg;
}

// Convert payload to "0" or "1"
let OneZero = (msg.payload === "true" || msg.payload === true) ? "1" : "0";

// Set the global variable
global.set(gname + ".State", OneZero);

// Debug output to help troubleshoot
node.log("Set global variable: " + gname + ".State = " + OneZero);

return msg;

You are comparing msg.payload with a string "true". Are you certain that the data is not boolean true?

Thank you for your suggestion. I found out what my disconnect was. I am using the node-red-contrib-state which, it turns out, is not connected to the global variables (although I thought it was). I found the answer here.

Thank you for your ideas and help.

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