Reputation: 238
I am trying to use this example from TCL wiki of server script:
# Initialise the state
after 5000 set state timeout
set server [socket -server accept 12345]
proc accept {args} {
global state connectionInfo
set state accepted
set connectionInfo $args
}
# Wait for something to happen
vwait state
# Clean up events that could have happened
close $server
after cancel set state timeout
# Do something based on how the vwait finished...
switch $state {
timeout {
puts "no connection on port 12345"
}
accepted {
puts "connection: $connectionInfo"
puts [lindex $connectionInfo 0] "Hello there!"
}
}
I want that after the clinet open a socket with the server one time then vwait loop will finish and continue run,in case it's fail I will have a timeout.so far so good. The problem began when for some reason and I get an error with $state and cant run it as a function with a script. the error I get is: can't read "state": no such variable.altough running its as not a function works properly and I cant understand why. can anyone help me to fix this issue please??
Upvotes: 0
Views: 39
Reputation: 137567
That code works, but only if it is evaluated in the global context; I guess you're trying to run it inside a procedure. What's happening is that the switch
invocation looks for a local variable state
instead of a global variable state
, and doesn't find it, whereas vwait
always works with global variables and after
callbacks are evaluated in the global scope.
The fix is to replace
switch $state {
with
switch $::state {
Assuming you're happy with using that variable for nothing else.
Upvotes: 1