Why doesn't tcl "if" return a value?

Why doesn't it work as I thought?

set x [if {1} {return 2} {return 3}] 

The output from the command shows 2 , but when you check the value of x , it looks like undefined ..!

I read the workaround ...

 proc give {x} {return $x} set x [if {1} {give 2} {give 3}] 

... but I do not understand why the first does not work.

From the tcl 8.5 documentation for if :

"The return value from the command is the result of the script body that was executed, or an empty string if none of the expressions were nonzero and there was no body N."

Questions:

  • Why does set x [if {1} {return 2} {return 3}] not set a value for x ?
  • Given that set x [if {1} {return 2} {return 3}] does not work, how tclsh display " 2 " in an interactive shell?
  • Given that tclsh displays " 2 " in an interactive shell, what does it look like, does set x remain undefined?
+4
source share
3 answers

See http://www.tcl.tk/man/tcl8.6/TclCmd/return.htm

Return codes are used in Tcl to control program flow. A tcl script is a sequence of Tcl commands. As each team score returns a return code TCL_OK , the score will continue the next command in the script. Any exceptional return code (not TCL_OK ) returned by the command evaluation causes the next command to terminate. The script evaluation terminates, and the exclusive return code from the command becomes the return code of the full evaluation script. This is the mechanism by which errors during script evaluation cause the call stack to be interrupted and expanded. It is also the mechanism by which commands, such as break , continue and return , invoke a script evaluation to complete without evaluating all the commands in the sequence.

Thus, the evaluation of the script is interrupted, x not installed, and 2 returned and printed as a result.

+7
source

The expr command returns a value, so

 set x [if 1 {expr 2} {expr 3}] 

But if you do this, you can also use the ternary operator

 set x [expr {1 ? 2 : 3}] 
+6
source

The reason why set x [if {1} {return 2} {return 3}] does not work as you expect is, as already noted, the fact that return is the command that causes the script to complete the evaluation. The workaround, using the give procedure, demonstrates that, by default, the return command completes level 1 of the call stack.

However, the "workaround" is indeed a pointless exercise in masochism: the return command allows you to specify where to return using the -level option introduced in Tcl 8.5. Try it, see how it works for you.

 set x [if {1} {return -level 0 2} {return -level 0 3}] 
+2
source

Source: https://habr.com/ru/post/1492618/


All Articles