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
To add the Python code and test out the project
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 |