return(n)
β¨ NAME β¨
return β bestie, this is the command that lets you bounce out of a procedure or set the return code of a script π
β¨
From the Tcl Built-In Commands manual, page return(n) π
πΈ SYNOPSIS πΈ
return ?result?
return ?-code code? ?result?
return ?option value ...? ?result?
π DESCRIPTION π
In its simplest usage, the return command is used without options in the body of a procedure to immediately return control to the caller of the procedure. If a result argument is provided, its value becomes the result of the procedure passed back to the caller. If result is not specified then an empty string will be returned to the caller as the result of the procedure. no cap π«Ά
The return command serves a similar function within script files that are evaluated by the source command. When source evaluates the contents of a file as a script, an invocation of the return command will cause script evaluation to immediately cease, and the value result (or an empty string) will be returned as the result of the source command. it's giving "exit stage left" energy π
π₯ EXCEPTIONAL RETURN CODES π₯
In addition to the result of a procedure, the return code of a procedure may also be set by return through use of the -code option. In the usual case where the -code option is not specified the procedure will return normally. However, the -code option may be used to generate an exceptional return from the procedure. code may have any of the following values:
ok(or0) β Normal return: same as if the option is omitted. The return code of the procedure is0(TCL_OK). β¨error(or1) β Error return: the return code of the procedure is1(TCL_ERROR). The procedure command behaves in its calling context as if it were the commanderror result. See below for additional options. πreturn(or2) β The return code of the procedure is2(TCL_RETURN). The procedure command behaves in its calling context as if it were the commandreturn(with no arguments). πbreak(or3) β The return code of the procedure is3(TCL_BREAK). The procedure command behaves in its calling context as if it were the commandbreak. πcontinue(or4) β The return code of the procedure is4(TCL_CONTINUE). The procedure command behaves in its calling context as if it were the commandcontinue. β‘οΈvalueβvaluemust be an integer; it will be returned as the return code for the current procedure. Applications and packages should use values in the range5to1073741823(0x3fffffff) for their own purposes. Values outside this range are reserved for use by Tcl. π’
When a procedure wants to signal that it has received invalid arguments from its caller, it may use return -code error with result set to a suitable error message. Otherwise usage of the return -code option is mostly limited to procedures that implement a new control structure. π§
The return -code command acts similarly within script files that are evaluated by the source command. During the evaluation of the contents of a file as a script by source, an invocation of the return -code code command will cause the return code of source to be code. π¦
π RETURN OPTIONS π
In addition to a result and a return code, evaluation of a command in Tcl also produces a dictionary of return options. In general usage, all option value pairs given as arguments to return become entries in the return options dictionary, and any values at all are acceptable except as noted below. The catch command may be used to capture all of this information β the return code, the result, and the return options dictionary β that arise from evaluation of a script. π
As documented above, the -code entry in the return options dictionary receives special treatment by Tcl. There are other return options also recognized and treated specially by Tcl. They are:
-errorcodelist β The-errorcodeoption receives special treatment only when the value of the-codeoption isTCL_ERROR. Then thelistvalue is meant to be additional information about the error, presented as a Tcl list for further processing by programs. If no-errorcodeoption is provided toreturnwhen the-code erroroption is provided, Tcl will set the value of the-errorcodeentry in the return options dictionary to the default value ofNONE. The-errorcodereturn option will also be stored in the global variableerrorCode. π-errorinfoinfo β The-errorinfooption receives special treatment only when the value of the-codeoption isTCL_ERROR. Theninfois the initial stack trace, meant to provide to a human reader additional information about the context in which the error occurred. The stack trace will also be stored in the global variableerrorInfo. If no-errorinfooption is provided toreturnwhen the-code erroroption is provided, Tcl will provide its own initial stack trace value in the entry for-errorinfo. Tcl's initial stack trace will include only the call to the procedure, and stack unwinding will append information about higher stack levels, but there will be no information about the context of the error within the procedure. Typically theinfovalue is supplied from the value of-errorinfoin a return options dictionary captured by thecatchcommand (or from the copy of that information stored in the global variableerrorInfo). π-errorstacklist β The-errorstackoption receives special treatment only when the value of the-codeoption isTCL_ERROR. Thenlistis the initial error stack, recording actual argument values passed to each proc level. The error stack will also be reachable throughinfo errorstack. If no-errorstackoption is provided toreturnwhen the-code erroroption is provided, Tcl will provide its own initial error stack in the entry for-errorstack. Tcl's initial error stack will include only the call to the procedure, and stack unwinding will append information about higher stack levels, but there will be no information about the context of the error within the procedure. Typically thelistvalue is supplied from the value of-errorstackin a return options dictionary captured by thecatchcommand (or from the copy of that information frominfo errorstack). π§-levellevel β The-leveland-codeoptions work together to set the return code to be returned by one of the commands currently being evaluated. Thelevelvalue must be a non-negative integer representing a number of levels on the call stack. It defines the number of levels up the stack at which the return code of a command currently being evaluated should becode. If no-leveloption is provided, the default value oflevelis1, so thatreturnsets the return code that the current procedure returns to its caller, 1 level up the call stack. The mechanism by which these options work is described in more detail below. π-optionsoptions β The valueoptionsmust be a valid dictionary. The entries of that dictionary are treated as additionaloption valuepairs for thereturncommand. π
π RETURN CODE HANDLING MECHANISMS π
Return codes are used in Tcl to control program flow. A Tcl script is a sequence of Tcl commands. So long as each command evaluation returns a return code of TCL_OK, evaluation will continue to the next command in the script. Any exceptional return code (non-TCL_OK) returned by a command evaluation causes the flow on to the next command to be interrupted. Script evaluation ceases, and the exceptional return code from the command becomes the return code of the full script evaluation. This is the mechanism by which errors during script evaluation cause an interruption and unwinding of the call stack. It is also the mechanism by which commands like break, continue, and return cause script evaluation to terminate without evaluating all commands in sequence. π
Some of Tcl's built-in commands evaluate scripts as part of their functioning. These commands can make use of exceptional return codes to enable special features. For example, the built-in Tcl commands that provide loops β such as while, for, and foreach β evaluate a script that is the body of the loop. If evaluation of the loop body returns the return code of TCL_BREAK or TCL_CONTINUE, the loop command can react in such a way as to give the break and continue commands their documented interpretation in loops. π
Procedure invocation also involves evaluation of a script, the body of the procedure. Procedure invocation provides special treatment when evaluation of the procedure body returns the return code TCL_RETURN. In that circumstance, the -level entry in the return options dictionary is decremented. If after decrementing, the value of the -level entry is 0, then the value of the -code entry becomes the return code of the procedure. If after decrementing, the value of the -level entry is greater than zero, then the return code of the procedure is TCL_RETURN. If the procedure invocation occurred during the evaluation of the body of another procedure, the process will repeat itself up the call stack, decrementing the value of the -level entry at each level, so that the code will be the return code of the current command level levels up the call stack. The source command performs the same handling of the TCL_RETURN return code, which explains the similarity of return invocation during a source to return invocation within a procedure. π§¬
The return code of the return command itself triggers this special handling by procedure invocation. If return is provided the option -level 0, then the return code of the return command itself will be the value code of the -code option (or TCL_OK by default). Any other value for the -level option (including the default value of 1) will cause the return code of the return command itself to be TCL_RETURN, triggering a return from the enclosing procedure. β
part 2 coming bestie, don't go anywhere πβ¨
πΈ EXAMPLES πΈ
Okay bestie, this is the part where it all clicks. Grab a snack π, because these little snippets are literally the whole vibe of return in action.
π The bare minimum glow-up
First up, a simple example of using return to return from a procedure, interrupting the procedure body.
proc printOneLine {} {
puts "line 1" ;# This line will be printed.
return
puts "line 2" ;# This line will not be printed.
}
See how return just... ends the whole thing right there? Line 2 never gets its moment. It's giving "the party's over, go home" and honestly, iconic behavior. π
β¨ Now with an actual value
Next, an example of using return to set the value returned by the procedure.
proc returnX {} {return X}
puts [returnX] ;# prints "X"
X goes in, X comes out. No cap, that's the whole trick. π¦
π₯ The "please give me valid input" one
Next, a more complete example, using return -code error to report invalid arguments.
proc factorial {n} {
if {![string is integer $n] || ($n < 0)} {
return -code error \
"expected non-negative integer,\
but got \"$n\""
}
if {$n < 2} {
return 1
}
set factor [factorial [expr {$n - 1}]]
set product [expr {$n * $factor}]
return $product
}
Not me yelling at you through an error code π If n isn't an integer or it's negative, we bounce out with -code error and a message that literally says expected non-negative integer, then but got "$n". The backslashes are just keeping that string glued together across lines, iykyk. π«Ά
π A homemade break
Next, a procedure replacement for break.
proc myBreak {} {
return -code break
}
Main character energy:</purl> we just made our own break and it slays. π₯
π Even lazier (affectionate)
With the -level 0 option, return itself can serve as a replacement for break, with the help of interp alias.
interp alias {} Break {} return -level 0 -code break
Zero new procedures, maximum chaos. Obsessed. β¨
π The "put it back how you found it" move
An example of using catch and return -options to re-raise a caught error:
proc doSomething {} {
set resource [allocate]
catch {
# Long script of operations
# that might raise an error
} result options
deallocate $resource
return -options $options $result
}
So we grab the resource, run the risky script, stash whatever came back in result and options, clean up the resource, and then re-throw the exact same error like nothing happened. Responsible and dramatic. π§
π The advanced final boss
Finally an example of advanced use of the return options to create a procedure replacement for return itself:
proc myReturn {args} {
set result ""
if {[llength $args] % 2} {
set result [lindex $args end]
set args [lrange $args 0 end-1]
}
set options [dict merge {-level 1} $args]
dict incr options -level
return -options $options $result
}
If there's an odd number of args, the last one is the result and we pop it off the list. Then we merge in {-level 1}, bump -level up by one with dict incr, and return -options. We built return inside return and it works. π
Periodt.
πΈ SEE ALSO πΈ
break(n), catch(n), continue(n), dict(n), error(n), errorCode(n), errorInfo(n), proc(n), source(n), throw(n), try(n)
Basically the entire friend group. Go say hi. π«Ά
πΈ KEYWORDS πΈ
break, catch, continue, error, exception, procedure, result, return
And that's the page, bestie!! π This whole thing ships with Tcl 8.5 and the man page itself is literally just return(n) β so yeah, same name as the command, very on brand. π Now go return something beautifully. π
π¦ where this page comes from
- alpine 3.23: tcl9-doc 9.0.3-r0 Β· TCL
- alpine 3.24: tcl9-doc 9.0.3-r2 Β· TCL
- fedora 43: tcl-doc 1:9.0.2-1.fc43 Β· TCL AND GPL-3.0-or-later WITH Bison-exception-2.2 AND BSD-3-Clause
- fedora 44: tcl-doc 1:9.0.2-1.fc44 Β· TCL AND GPL-3.0-or-later WITH Bison-exception-2.2 AND BSD-3-Clause
- nixos 26.05: tcl 9.0.3
- Copyright (c) 1993 The Regents of the University of California
- Copyright (c) 1994-1996 Sun Microsystems, Inc
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms