Setting a global value to the state of a component - then using it

I’m not clear how to set a global variable to the state of a component, and then how to use that variable in log statements and in other functions.

I have a Text Component, message_text, and I want to access the state of this component, put it into a global variable, report the result in a log statement, and be able to use that global variable in other functions.

I’m doing this within a button component:

button:
  - platform: template
    id: update_screen
    name: "Update Screen"
    web_server:
      sorting_group_id: group_main_controls
      sorting_weight: 30
    on_press:
      then:
        - logger.log: "Updating screen"
        - globals.set:
            id: g_test
            value: !lambda return id(message_text).state;
        - logger.log:
            format: "Test value of message text: %s"
            args: "g_test"
        - lvgl.label.update:
            id: InfoDisplay
            text: !lambda |-
              std::size_t pos;
              std::string str = id(message_text).state;
              while ((pos = str.find("\\n")) != std::string::npos)
                str.replace(pos, 2, "\n");
              return str;

Note that I access that same state later, in the code where I update an LVGL widget (“InfoDisplay”) and I’m not having any trouble there.

With the global variable, “g_test”, I’m just trying to get the string value of the state and report it in a log statement. When I do, I get gibberish as output (see the last line here):


I’ve tried using c_str() to get the string info in the lambda, although I didn’t expect it to work. I’ve tried enclosing g_test in double quotes, single quotes, double quotes in single quotes and I still get the gibberish. (Except when I use double quotes in single quotes - then I get “g_test” in the log statement.)

I’m not sure if I’m not getting the proper string value of the state of message_text or if I’m not using the right formatting to make sure the value of g_test prints properly.

Also, I’d like to get this value once and not multiple times (note that I use a different lambda to get it later - I’d rather get it once and then use the global variable to set the value of InfoDisplay. If I can’t be sure I’m getting the right value or how to do it, I can’t count on being able to use the global variable for anything.

So

  1. What am I doing wrong to get the value and print it in the log statement?
  2. Will fixing that mean I could, later, do this:
- lvgl.label.update:
            id: InfoDisplay
            text: "g_text"

which would let set the text in InfoDisplay to the value of the global variable g_text?

You refer to a global using id(global_name), but string globals are a total pain - you are a better man than me if you can get them to work.