piper
piper

Reputation: 87

How to define a constant in tclsh

I would like to define a constant as a flag in tclsh, but ordinary variables can be changed, how can I generate a constant.

Upvotes: 1

Views: 145

Answers (1)

Donal Fellows
Donal Fellows

Reputation: 137797

I've been thinking about that. The classic technique is to use a trace to make writes and unsets fail (except if the containing context — namespace or procedure body or interpreter — is also going) but that has a lot of overhead, especially in procedures (local variable traces are not well optimised because they are uncommon).

set myConst 12345
proc myConstReset {var args} {
    upvar 1 $var v
    set $v 12345
    error "$var is constant"
}
trace add variable myConst {write unset} myConstReset

More often, if that is to emulate something like an enum in other languages (such as C++ and C#), then it is better to use symbolic names at the Tcl level. (Numbers are just the how those things are implemented in those other languages.) You'd then look up the name to value mapping when you needed to translate it. In Tcl, you might use an array or dictionary for that. In the C API, Tcl_GetIndexFromObjStruct() is highly relevant and well optimised for these sorts of tasks (ending up nearly as efficient as an integer index, but oh so more readable).

But not always. I definitely think it would be a good idea to add support for defining named constants in Tcl, that would be syntactically read like variables, except more efficient. (I would love this for defining complex regular expressions, for example.) Not that that exists as anything other than a vague idea in my head right now. Hmm...

Upvotes: 1

Related Questions