2
votes

I have a curious case of Tcl that perhaps I just don't understand. The following code is done at the top level (not inside of any procedure):

if {![info exists g_log_file_name]} {
    set g_log_file_name "default.txt"
}

What I hope it would do is to declare a global variable with some value if it wasn't declared yet (which can be done at some other script or C application). However, the if statement always false. I ran on Tcl 7.4.

What may be the problem?

Thank you so much.

1

1 Answers

8
votes
% info level
0
% info exists g_log_file_name
0
% set g_log_file_name whatever
whatever
% info exists g_log_file_name
1

Hence the reason you observe is probably because the variable is really always unset at the time your if command is executed.

Possible reasons for this I can imagine are:

  • It's just not set: literally, no code attempt to do this;
  • The external code sets some other variable: name mismatch;
  • The external code sets a variable in some other interpreter: in a C code embedding Tcl, there can be any number of Tcl interpreters active at any moment (and those are free to create child interpreters as well);

I'm not sure abot the long forgotten version of Tcl you have at hand, but 8.x has the trace command which can be used to log accesses to a particular variable—you could try to use it to see what happens.