Initialize
The initialize function is called before all other functions on script start. So here you can check your variables, set or update input and output parameters, and if you encounter any errors while initializing, you can return false to prevent the script from running.
There are two variants of this function in AngelScript version of PnS API:
The second version (which returns bool) exists in both AngelScript and C++ APIs, is more powerful, so I suggest you use that.
For example, while initializing you can check the sampleRate, and if your script doesn't support it, you can return false to prevent script from running. If everything is fine return true.
Initialize function is a place where you can update attributes of input and output parameters (and strings), so you can make a very cozy function for adding parameters, like explained in the article "How to add parameters conveniently".
ALERT
In some cases (I've seen it on Mac C++ API for example) the initialize function can be called twice. So if you are doing something that relies on previous state of variables, like adding value to the end of array, be aware, cause it can be added twice. To not get in trouble, set a flag to check if initialize was already executed.
Important for native API
Initialize is particularly important for C++ API, because it's the place where your sampleRate, audioInputsCount and other variables are initialized and set. In comparison, in AngelScript API you can use sampleRate and other variables while constructing global variables, like that:
- // in AngelScript you can already use variables like sampleRate etc.
- string name = "My script";
- uint halfASecondInSamples = uint(sampleRate / 10.0);
- uint totalInputChannels = audioInputsCount + audioInputsAuxCount;
- // ...
- return true;
- }
In C++ API you have to do it in initialize, like this.
- // in C++ you only declare them here
- DSP_EXPORT string name = "My script";
- DSP_EXPORT uint audioInputsCount=0;
- DSP_EXPORT uint audioInputsAuxCount=0;
- DSP_EXPORT double sampleRate=0;
- uint halfASecondInSamples;
- uint totalInputChannels;
- // and their values are accessible not earlier than initialize call
- // here global API vars like sampleRate, audioInputsCount etc are already set.
- halfASecondInSamples; = sampleRate / 10.0;
- totalInputChannels = audioInputsCount + audioInputsAuxCount;
- return true;
- }
In my experience, initialize function can be also called when user is changing sampleRate, buffer size, etc. So from script point of view it's much like restarting a script.
Initialize and shutdown
Initialize seems a proper place to open files, load libraries (for C++ API), initialize objects, etc.
To close files, free resources, there a complementary shutdown function. It is mostly useful for C++ PnS API (here you can delete what was created with new, close file handles, etc).