Introduction

The internal BrainStim script engine uses a garbage collection method to reclaim memory used by the script objects when they are no longer needed. An object's memory can be automatically reclaimed when it is no longer referenced anywhere in the scripting environment context by the script engine garbage collector. If all referenced (allocated) memory is successfully reclaimed and the script context ends then the internal BrainStim script engine automatically exits. If this is not the case then the script remains in a running state and thus does not end and the script 'hangs' (waits...) and to proceed we'll need to manually restart it.

Guidelines

For the garbage collection to work properly you need to make sure that you follow the following guidelines before ending the script context:

  1. Disconnect all previous made signal/slot connections (signal slot connections are described in this document) using the disconnect statement.
  2. Set all previously dynamic constructed object (where you used the new keyword) to null.
  3. Set all previously defined script functions to null.
  4. At last call the BrainStim.cleanupScript() function to force a remaining automatic garbage collection to make sure that all the claimed script memory is released.

Example

Let's use an example to examine the above in more detail.

  1. Start BrainStim.
  2. Open the GarbageCollection.qs file located in the Main Program Directory under the subfolder \Examples\BrainStim\QtScript GarbageCollection\.
  3. Examine the QtScript code and notice that:
    • a QTimer object is created using the new keyword
    • this newly created QTimer object is then connected trough a signal/slot connection to a local script function
    • Every time this function is then automatically called by the QTimer object a variable is decremented and checked if it's lower than 0, if so then a ScriptCleanupFunction function is called to perform a script garbage collection using the above guidelines.
  4. Execute (press the F5 key) the QtScript code see what happens and wait till the script automatically ends.
  5. Let's see what happens if we don't follow the above guidelines. Comment (by writing "//"  before the codeline) the line where the QTimer object is disconnected from the local function inside the ScriptCleanupFunction function.
  6. Execute (press the F5 key) the QtScript code again and notice that the script doesn't automatically end this time. The Execute command from the Document menu (or the corresponding toolbar button) stays disabled. This button is automatically enabled again by the internal script engine when the script could successfully performed a Garbage Collection.
  7. Click on the Restart Script Engine button to manually restart the whole script engine.