#### 1.2.3 Conditional Execution ¶

The design of the `q_out` function can be improved. As written, each output file will contain only a single wave. You might want the option of writing several waves into a single file. Consider this alternative:

    func q_out(Q, file)
    {
      if (structof(file)==string) file = create(file);
      write, file, "Q = "+pr1(Q);
      write, file, "   theta       amplitude";
      write, file, theta, damped_wave(theta,Q);
      return file;
    }

The `if` statement executes its body (the redefinition of `file`) if and only if its condition (`structof(file)==string`) is true. Any scalar number may serve as a condition – a non-zero value is “true”, and the value zero is “false”.

The `structof()` function returns the data type object when its argument is an array, and nil (`[]`) otherwise. In particular, if `file` is a text string (like `"q.out"`), `structof` returns string, which is the data type of strings. The binary operator `==` (as distinguished from assignment `=`) tests for equality, returning “true” or “false”. Note that the test works even for non-numeric objects, like the data type string.

Hence, if the `file` argument is a string, the new `q_out` presumes it is the name of a file, which it creates, redefining `file` as the associated file object. Thus, after the first line of the function body, `file` will be a file object, even if a file name was passed into the function. Furthermore, since the parameter `file` is local to `q_out`, none of this hocus pocus will have any effect outside `q_out`.

The second trick in the new `q_out` is the reappearance of a `return` statement. The original calling sequence:

    q_out, 3, "q.out"

has the same result as before – the `if` condition is true, so the file is created, then the wave data is written. This time the file object is returned, only to be discarded because `q_out` was invoked as a procedure. When the file object disappears, the file closes. But if `q_out` were invoked as a function, the file object can be saved, which keeps the file open:

    f = q_out(3,"q.out")
    q_out,2,f
    q_out,1,f
    close,f

Now the file `q.out` contains the Q=3 wave, followed by the Q=2 and Q=1 waves. In the second and third calls to `q_out`, the `file` parameter is already a file object, so the `if` condition is false, and `create` is not called. Notice that the file does not close when the return value from the second (or third) call is discarded; the variable `f` refers to the same file object as the discarded return value. Without an explicit call to `close`, a file only closes when the final reference to it disappears.