user3636706
user3636706

Reputation: 207

Can anyone explain me [list source file]?

I have been using Tcl language for 2 months. I have a question: what does [list source file] mean? I understand source and list separately, but I do not understand what it means when they are put together.

Upvotes: 3

Views: 818

Answers (1)

Donal Fellows
Donal Fellows

Reputation: 137757

That would appear to be using list to do command-script construction. I'd bet that the result of that [list source file] is then used with uplevel or namespace eval. Or possibly even interp eval.


The list command makes lists. It also makes substitution-free commands, so that:

eval [list $a $b]

is effectively identical in behaviour to:

$a $b

In your case, we have source instead of $a and file (which I'd lay strong odds on not being that literal) instead of $b. Why would we do this? Well, it ensures that if the file name has Tcl meta-characters in it (e.g., {) then the created script to source the file in won't have any problems at all when evaluated.

Why wouldn't you just write source file directly? Well, the most likely cases are where you want to source into a context other than the current one; the source command reads the file into a string and then effectively does an immediate eval on that string (well, there's some nuances, but it's surprisingly close to that). In particular:

proc foo {} {
    source bar.tcl
}

Will run the contents of bar.tcl inside the procedure body of foo, just as if you'd typed the text in there directly. The variables will be local variables (unless you use global or something like that) and so on. Most people don't write Tcl scripts that like that sort of treatment, frankly; to handle this, and make the code evaluate in a defined context, you'd actually write:

proc foo {} {
    # Quoted to defeat the Stack Overflow syntax highlighter only!
    uplevel "#0" [list source bar.tcl]
}

Upvotes: 4

Related Questions