diff options
author | dgp <dgp@users.sourceforge.net> | 2019-06-10 18:58:44 (GMT) |
---|---|---|
committer | dgp <dgp@users.sourceforge.net> | 2019-06-10 18:58:44 (GMT) |
commit | 6a3773f6119ffaee96382a12d282e033a6a0bf95 (patch) | |
tree | d8226b15d6b95deacff92cf94a60000ec5b7a39a /doc/expr.n | |
parent | c6cb158e39e58c0780cadfe0d2565ae94e79767e (diff) | |
download | tcl-6a3773f6119ffaee96382a12d282e033a6a0bf95.zip tcl-6a3773f6119ffaee96382a12d282e033a6a0bf95.tar.gz tcl-6a3773f6119ffaee96382a12d282e033a6a0bf95.tar.bz2 |
Doc formatting and advice about double substitution in expressions.
Diffstat (limited to 'doc/expr.n')
-rw-r--r-- | doc/expr.n | 26 |
1 files changed, 23 insertions, 3 deletions
@@ -343,25 +343,45 @@ substitution on the value before \fBexpr\fR is called. In the following example, the value of the expression is 11 because the Tcl parser first substitutes \fB$b\fR and \fBexpr\fR then substitutes \fB$a\fR. Enclosing the expression in braces would result in a syntax error. +.PP .CS set a 3 set b {$a + 2} \fBexpr\fR $b*4 .CE .PP - -When an expression is generated at runtime, like the one above is, the bytcode +When an expression is generated at runtime, like the one above is, the bytecode compiler must ensure that new code is generated each time the expression is evaluated. This is the most costly kind of expression from a performance perspective. In such cases, consider directly using the commands described in the \fBmathfunc\fR(n) or \fBmathop\fR(n) documentation instead of \fBexpr\fR. - +.PP Most expressions are not formed at runtime, but are literal strings or contain substitutions that don't introduce other substitutions. To allow the bytecode compiler to work with an expression as a string literal at compilation time, ensure that it contains no substitutions or that it is enclosed in braces or otherwise quoted to prevent Tcl from performing substitutions, allowing \fBexpr\fR to perform them instead. +.PP +If it is necessary to include a non-constant expression string within the +wider context of an otherwise-constant expression, the most efficient +technique is to put the varying part inside a recursive \fBexpr\fR, as this at +least allows for the compilation of the outer part, though it does mean that +the varying part must itself be evaluated as a separate expression. Thus, in +this example the result is 20 and the outer expression benefits from fully +cached bytecode compilation. +.PP +.CS +set a 3 +set b {$a + 2} +\fBexpr\fR {[\fBexpr\fR $b] * 4} +.CE +.PP +In general, you should enclose your expression in braces wherever possible, +and where not possible, the argument to \fBexpr\fR should be an expression +defined elsewhere as simply as possible. It is usually more efficient and +safer to use other techniques (e.g., the commands in the \fBtcl::mathop\fR +namespace) than it is to do complex expression generation. .SH EXAMPLES .PP A numeric comparison whose result is 1: |