How publish a variable from that's defined inside lambda

Hello i try to publish a text sensor, the content is a float … it’s calculated this way:

       - lambda: |-
            static std::vector<uint16_t> buffer;
            static const size_t BLOCK_SIZE = 256;
            if (id(sock_fd) < 0) {
              buffer.clear();
              buffer.shrink_to_fit();
            } else {
              buffer.reserve(BLOCK_SIZE);
              for (const uint16_t sample : x) {
                buffer.push_back(sample);
                float sum = 0;                  
                if (buffer.size() >= BLOCK_SIZE) {
                  for (int i = 0; i < BLOCK_SIZE; i++) {
                    sum+= buffer[i];
                    }
                  sum = sum / BLOCK_SIZE;
                  (void) ::send(id(sock_fd), buffer.data(), buffer.size() * sizeof(uint16_t), 0);
                  buffer.clear();
                  buffer.reserve(BLOCK_SIZE);
                }
              }
            }

how can I bring sum to a text sensor ?
i tried many different suggestions but , they are mostley for yaml and i am in Lamda ( C - Language ) … it looks like is not working to mix inside lambda.
And ouside my sum is gone.
I tried it with globals but i get only error with the yaml syntax. can you give me a little hint how i can fiy my problem ?

publish_state, I guess