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:
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:
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.