How to set a variable in an action

I am trying to create a script that returns a variable. Within it’s sequence, the variable is defined as:

  - variables:
      return: |
        {% set speaker_original_state = states(sensor.desktop_speaker_muted) %}
        {% set desired_state = mute %}
        {% set toggled = false %}

I want to be able to change its value based on a condition. I have tried multiple syntaxes, all to no avail, such as,

    - action: template
      value_template: "{% set return.toggled = true %}"

What is the correct way to set the variable?

Clarify what you are actually trying to do. Do you mean return a variable’s value within the script or return it to a different script or automation, i.e. a response_variable?

You seem to be confusing script variables and Jinja variables. Your script variable, return, has no value, because the templating contains no expressions, only statements. If you want return to contain a dictionary there are two ways to do it, in YAML or in Jinja.

To do it in YAML you would use the following:

  - variables:
      return:
        speaker_original_state: "{{states('sensor.desktop_speaker_muted') }}"
        desired_state: "mute"
        toggled: false

To do it in Jinja:

  - variables:
      return: |
        {{ {"speaker_original_state": states('sensor.desktop_speaker_muted'),
        "desired_state": "mute", "toggled": false} }}

That’s not a thing… there are numerous examples of using templating in actions to retrieve variable values in the Script Syntax docs