Example 2

This example demonstrates how to invoke a procedure every time a primitive fires.

Consider the following design in the SDF domain.

System model of TclScript demo

Suppose the Tcl script for the TclScript primitive reads:

proc goTcl_$starID {starID} {
    set inputVals [grabInputs_$starID]
    set xin [lindex $inputVals 0]
    set yin [lindex $inputVals 1]
    setOutputs_$starID [expr $xin+$yin]
}

Unlike the previous example, this script does not define any code that runs when the script is sourced, during the setup phase of execution of the primitive. Instead, it simply defines a procedure with a name unique to the instance of the primitive. This procedure reads two input values, adds them, and writes the result to the output. Although this would be a very costly way to accomplish addition in MLDesigner, this example nonetheless illustrates an important point. If a Tcl script sourced by a TclScript primitive defines a procedure called goTcl_$starID, then that procedure will be invoked every time the primitive fires. The single argument passed to the procedure when it is called is the starID. In this example, the procedure uses grabInputs_$starID, defined by the TclScript primitive, to read the inputs. The current input values are returned by this procedure as a list, so the Tcl command lindex is used to index into the list. The final line adds the two inputs and sends the result to the output.


As shown in this example, if the Tcl script defines the optional Tcl procedure goTcl_$starID, then that procedure will be invoked every time the primitive fires. It takes one argument (the starID) and returns nothing. This procedure, therefore, allows for synchronous communication between the MLDesigner simulation and the Tcl code (it is synchronized to the firing of the primitive). If no goTcl_$starID procedure is defined, then communication is asynchronous (Tcl commands are invoked at arbitrary times, as specified when the script is read). For asynchronous operation, typically X events are bound to Tcl/Tk commands that read or write data to the primitive.

The inputs to the primitive can be of any type. The print() method of the particle is used to construct a string passed to Tcl. Although it is not illustrated in the above examples, asynchronous reads of the primitive inputs are also allowed.