Using the state variable to store a value persistently

Each Live Python block has a built in variable called state, which is initialized to zero when the project is first emulated or deployed, but retains its value while the project is running. Unlike variables initialized inside the Live Python block, the value of state will be retained even when the input values change, and the Python code is executed repeatedly.

The example in this section will show how the value of state can be incremented by successive calls to the Python code. The calls are initiated by a button wired to an input on the Live Python block. Each time the button is clicked, the Python code will run. The changing value of state is displayed on the control surface of the Live Python block.

Tip: If you need to save more variable values than just that of the state variable, you can store the values using generic controls. For more information, see Storing and reusing values from Python code.

To use the persistent state variable

  1. Add a NION to your project.
  2. Expand the device tree to display Control / Knobs, Faders Etc. / Generic Controls.
  3. Drag a Generic Controls device over to the design page.
  4. In the Type of control(s) list, click boolean.
  5. Click OK.
  6. Double-click the control block to open it, then copy the button control out to the design page.
  7. Click the button to select it, and then press SHIFT+CTRL+M to add a master wiring node.
  8. Expand the device tree to display Control / Live Python.
  9. Drag the Live Python folder over to the design page, and then click 1 input - 0 output.
  10. On the toolbar, click the Wire Mode button to switch to wiring mode.
  11. Drag the master wiring node on the button over to the input wiring node on the Live Python block to wire the devices together.

To add the Python code and test out the project

  1. Emulate the project.
  2. Double-click the Live Python block to open it.
  3. Double-click the Edit button to open the Python source code editor.
  4. Type the code below into the editor and then save the file.

    message.string_set("this function has been called " + str( state ) + " times" )

    state = state + 1

    Each time you click the button, the message on the control surface of the Python block will be updated.

See also

Controlling the execution of Python code

Storing and reusing values from Python code

Using threading to run scripts autonomously