esphome / issues

Issue Tracker for ESPHome
https://esphome.io/
290 stars 35 forks source link

Script parameters cannot be modified by nested lambdas #3798

Open chatziko opened 1 year ago

chatziko commented 1 year ago

The problem

Script parameters are an awesome new feature! I was expecting to be able to do something like:

script:
- id: my_script
  parameters:
    steps: int
  then:
  - while:
      condition:
        lambda: 'return steps > 0;'
      then:
      - ...do something...
      - delay: 5ms
      - lambda: 'steps--;'

But this creates a hard to spot infinite loop! Cause the nested lambda is translated to:

  lambdaaction_16 = new LambdaAction<int>([=](int steps) -> void {
      steps--;
  });

so steps is a local variable of the lambda, and steps-- has no effect!

This will likely create hard to spot bugs and frustration, it is very reasonable to expect to be able to modify paramerts. I see two solutions:

  1. Ideally, pass steps by reference in the nested lambda, so that it can be modified (not sure if this creates issues elsewhere, though)
  2. Accept that parameters are read-only, documentit, and declare steps as const so that the compiler does not allow you to modify it.

(Note that this wouldn't be an issue if the whole script body is pure c++ code, but in this example I need a "yaml while" to be able to use delay.)

Which version of ESPHome has the issue?

2022.11.1

What type of installation are you using?

Home Assistant Add-on

Which version of Home Assistant has the issue?

2022.11

What platform are you using?

ESP32-IDF

Board

No response

Component causing the issue

No response

Example YAML snippet

No response

Anything in the logs that might be useful for us?

No response

Additional information

No response

github-actions[bot] commented 1 year ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

Masterz69 commented 6 months ago

Looks script parameters are not passed to each lambdas in script. Recently repored : https://community.home-assistant.io/t/question-for-scripts-with-parameter/715246

Have done little script:

script:
  - id: zzz
    mode: restart
    parameters:
      temp: float
    then:
      - lambda: if (temp > id(boil_anti_climate).target_temperature_low) {  } else {  }
      - if:
          condition:
            for:
              time: 10s
              condition:
                - lambda: return temp > id(boil_anti_climate).target_temperature_low;
          then:

Script parameter temp is working in first lambda, but included in condition tharow an error:

Compiling .pioenvs/zzz-d1mini/src/main.cpp.o
<unicode string>: In lambda function:
<unicode string>:275:14: error: 'temp' was not declared in this scope