global(3tcl)

πŸ“¦
version 9.0.4 Β· 2 versions
, in debian trixie, ubuntu questing, ubuntu resolute, ubuntu stonking

✨ global β€” Access global variables ✨

okay bestie, gather round πŸ’– this is global, a Tcl built-in command, and it's literally the little fairy godmother that lets your proc reach out and touch the global scope. 🧚


🌸 SYNOPSIS 🌸

global ?varname ...?

short, sweet, and absolutely carrying the whole show πŸ’…


πŸ¦‹ DESCRIPTION πŸ¦‹

Okay so real talk: this command has no effect unless it's executed in the context of a proc body. Like, if you're not inside a proc, it's giving nothing. It's just vibing. 😭

But the second you are inside a proc body? iconic behavior ✨ It creates local variables that are linked to the corresponding global variables. The way that works is exactly like those linked variables created by upvar β€” and here's the tea β€” those linked variables are not included in the list returned by info locals. So don't go looking for them there, they're not on that guest list. πŸ™ˆ

Now, if varname contains namespace qualifiers, then the local variable's name is the unqualified name of the global variable, as determined by the namespace tail command. So it trims the whole qualifier situation off and just uses the tail end. βœ‚οΈ

And important: varname is always treated as the name of a variable, not an array element. So if the name looks like an array element β€” like, say, a(b) β€” you get an error. Full stop. Periodt. πŸ’€


πŸŽ€ EXAMPLES πŸŽ€

🌟 Example the first: setting a namespace variable

This procedure sets the namespace variable ::a::x πŸ‘‘

proc reset {} {
    global a::x
    set x 0
}

see how it says global a::x but then sets x? yeah. that's the namespace tail thing doing its thing. slay. πŸ’…

🌟 Example the second: the accumulator

This procedure accumulates the strings passed to it in a global buffer, separated by newlines. 🌈

It's useful for situations when you want to build a message piece-by-piece (as if with puts) but send that full message in a single piece β€” for example, over a connection opened with socket, or as part of a counted HTTP response. πŸ“¬

proc accum {string} {
    global accumulator
    append accumulator $string \n
}

building it up bit by bit and then dropping the whole thing at once? that's main character energy fr fr. 🫢


πŸ’œ SEE ALSO πŸ’œ

go read those too, they're all part of the same friend group πŸ“


⭐ KEYWORDS ⭐

global, namespace, procedure, variable


and that's the whole vibe check, bestie. go forth and scope responsibly. πŸ¦‹

this page came from the Tcl crew, documenting global(3tcl) β€” sending you all the love from the Tcl Built-In Commands corner of the manual. mwah. πŸ’–

πŸ“¦ where this page comes from