Skip to content
Tcl Source Code Artifact [638b2ac19a]
Login

Artifact [638b2ac19a]

Artifact 638b2ac19ac468a023ee19390c1d848d668ddc1dd3953968d9358f08ebcad512:


'\"
'\" Copyright (c) 2023 Donal K. Fellows
'\"
'\" See the file "license.terms" for information on usage and redistribution
'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
'\"
.TH const n 9.0 Tcl "Tcl Built-In Commands"
.so man.macros
.BS
'\" Note:  do not modify the .SH NAME line immediately below!
.SH NAME
const \- create and initialize a constant
.SH SYNOPSIS
\fBconst \fIvarName value\fR
.BE
.SH DESCRIPTION
.PP
This command is normally used within a procedure body (or method body, 
or lambda term) to create a constant within that procedure, or within a 
\fBnamespace eval\fR body to create a constant within that namespace. 
The constant is an unmodifiable variable, called \fIvarName\fR, that is 
initialized with \fIvalue\fR.
.PP
If a variable \fIvarName\fR does not exist, it is created.
If the variable already exists, it is set to \fIvalue\fR.
The variable is marked as a constant; this means that no other command
(e.g., \fBset\fR, \fBappend\fR, \fBincr\fR, \fBunset\fR)
may modify or remove the variable; variables are checked for whether they 
are constants before any traces are called.
.PP
The \fIvarName\fR may not be a qualified name or reference an element of an 
array by any means. If the variable exists and is an array, that is an error.
.PP
Constants are normally only removed by their containing procedure exiting or 
their namespace being deleted.
.SH EXAMPLES
.PP
Create a constant in a procedure:
.PP
.CS
proc foo {a b} {
    \fBconst\fR BAR 12345
    return [expr {$a + $b + $BAR}]
}
.CE
.PP
Create a constant in a namespace to factor out a regular expression:
.PP
.CS
namespace eval someNS {
    \fBconst\fR FOO_MATCHER {(?i)}\emfoo\eM}

    proc findFoos str {
        variable FOO_MATCHER
        regexp -all $FOO_MATCHER $str
    }

    proc findFooIndices str {
        variable FOO_MATCHER
        regexp -all -indices $FOO_MATCHER $str
    }
}
.CE
.PP
Making a constant in a loop doesn't error:
.PP
.CS
proc foo {n} {
    set result {}
    for {set i 0} {$i < $n} {incr i} {
        \fBconst\fR X 123
	lappend result [expr {$X + $i**2}]
    }
}
.CE
.SH "SEE ALSO"
proc(n), namespace(n), set(n), unset(n)
.SH KEYWORDS
namespace, procedure, variable, constant
.\" Local variables:
.\" mode: nroff
.\" fill-column: 78
.\" End: