Hey folks, I am a long time HA user, and I am finally digging in to native scripting. Not Node Red or the Python add ons - nothing wrong with those, I just want to understand the native scripting architecture. I have spent a bit of time trying to wrap my head around variables and I think they can be summarized as: Locally scoped to the current and descendant sequences, final, and shadowed. The first is I think fairly uncontroversial - it’s specifically documented that way, but the other two bear some clarification.
By final
I mean the value of a variable will be calculated exactly once when it is defined, and never modified. If it is templated, changes that would modify the result of the template will not alter the variable. There is also no way to write a new value to an existing variable. This is the same as Java final
.
By shadowed
I mean the that a new variable with the same name as an existing one can be created even when the other variable is in scope. The value of the new variable will be used when the name is used, but the old value will return once the shadowing variable leaves scope. This is what appears to be happening in the variable scope example of the docs - people
can be read in the sub-sequence, and a new variable called people
can be defined, but when we return to the outer sequence the original value of people
reappears.
Does this sound about right? Also note that I am not discussing the various variable add ons that exist, just the vanilla ones that are in the built in scripting language.
Assuming this is correct, I think it means you can’t modify variables in an if-then-else
block, since the variable definitions will be locally scoped to the then
or else
blocks. As a work around, templates can be used instead, e.g.:
- variables:
foozle: |
{% if is_state("light.kitchen_accent", "off") -%}
dark
{%- else -%}
light
{% endif %}