Formulas 1.8. Formulas in scripts

In scripts, you can assign numeric expressions to numeric variables, string expressions to string variables, and array expressions to array variables. You can also use numeric, string and array variables in expressions.

Example: report a square

Choose New Praat script from the Praat menu. A script editor window will become visible. Type the following lines into that window:

    x = 99
    x2 = x * x
    writeInfoLine: “The square of ”, x, “ is ”, x2, “.”

This is an example of a simple Praat script; it assigns the results of the numeric formulas 99 and x * x to the numeric variables x and x2. Note that the formula x * x itself refers to the variable x. To run (execute) this script, type Command-R or choose Run from the Run menu. Praat will then write the following text into the Info window:

    The square of 99 is 9801.

For more information on scripts, see the Scripting tutorial.

Example: rename the city of Washington

Type the following text into the script editor window:

    current$ = “Bush”
    previous$ = “Clinton”
    famous$ = “Lincoln”
    newCapital$ = current$ + mid$ (famous$, 2, 3) + right$ (previous$, 3)
    writeInfoLine: “The new capital will be ”, newCapital$, “.”

This script assigns the results of four string expressions to the four string variables current$, previous$, famous$, and newCapital$. The dollar sign is the notation for a string variable or for a function whose result is a string (like left$). Note that the formula in the fourth line refers to three existing variables.

To see what the new name of the capital will be, choose Run.

Example: report five squares

Type the following script:

    x# = { 1, 2, 3, 4, 5 }
    x2# = x# * x#
    writeInfoLine: “The squares of ”, x#, “ are ”, x2#, “.”

Praat will then write the following text into the Info window:

    The squares of 1 2 3 4 5 are 1 4 9 16 25.

Example: numeric expressions in settings in scripts

As in real settings windows, you can use numeric expressions in all numeric fields. The example of two pages back becomes:

    Create Sound from formula: “sine”, 1, 0, 10000 / 44100, 44100, ~ 0.9 * sin (2*pi*377*x)

Example: string expressions in settings in scripts

As in real settings windows, you can use string expressions in all text fields:

    soundName$ = “hello”
    Read from file: soundName$ + “.wav”

Example: numeric expressions in creation in scripts

Suppose you want to generate a sine wave whose frequency is held in a variable. This is the way:

    frequency = 377
    Create Sound from formula: “sine”, 1, 0.0, 1.0, 44100, ~ 0.9 * sin (2*pi*frequency*x)

In this example, Praat will protest if x is a variable as well (x), because that would be ambiguous with the x that refers to the time in the sound (see Formulas 1.7. Formulas for modification).

Links to this page


© ppgb 20170916