Previous section   Next section

Practical Programming in Tcl & Tk, Third Edition
By Brent B. Welch

Table of Contents
Chapter 16.  Event-Driven Programming

The vwait Command

The vwait command waits until a variable is modified. For example, you can set variable x at a future time, and then wait for that variable to be set with vwait.

set x 0
after 500 {set x 1}
vwait x

Waiting with vwait causes Tcl to enter the event loop. Tcl will process events until the variable x is modified. The vwait command completes when some Tcl code runs in response to an event and modifies the variable. In this case the event is a timer event, and the Tcl code is simply:

set x 1

In some cases vwait is used only to start the event loop. Example 16-2 sets up a file event handler for stdin that will read and execute commands. Once this is set up, vwait is used to enter the event loop and process commands until the input channel is closed. The process exits at that point, so the vwait variable Stdin(wait) is not used:

Example 16-2 Using vwait to activate the event loop.
proc Stdin_Start {prompt} {
   global Stdin
   set Stdin(line) ""
   puts -nonewline $prompt
   flush stdout
   fileevent stdin readable [list StdinRead $prompt]
   vwait Stdin(wait)
proc StdinRead {prompt} {
   global Stdin
   if {[eof stdin]} {
   append Stdin(line) [gets stdin]
   if {[info complete $Stdin(line)]} {
      catch {uplevel #0 $Stdin(line)}result
      puts $result
      puts -nonewline $prompt
      flush stdout
      set Stdin(line) {}
   } else {
      append Stdin(line) \n

      Previous section   Next section