classvariable(3tcl)

πŸ“¦
version 9.0.4 Β· 3 versions
, in ubuntu stonking

πŸ’– classvariable β€” the TclOO glow-up for class-wide variables πŸ’–

okay bestie, so this is classvariable from the TclOO manual (that's the classvariable(3tcl) page, section 3tcl, TclOO Commands β€” you're in the right place, don't worry 🫢).


✨ NAME ✨

classvariable β€” Create link from local variable to variable in class


🌸 SYNOPSIS 🌸

package require tcl::oo

classvariable variableName ?...?

πŸ¦‹ DESCRIPTION πŸ¦‹

so. the classvariable command. it's only available inside methods β€” like, it lives in method scope, that's its whole thing, no cap. πŸ’…

you hand it a series of one or more variable names, and it makes those names available in the method's scope. super easy.

but here's the rules, and they matter:

  • those variable names must not be qualified β€” no dotted paths, no namespaces, none of that πŸ™…
  • and they must not refer to array elements β€” so no foo(bar) situation

and where do the variables actually live? the originating scope is the namespace of the class that the method was defined by. so basically: the variables you're linking are shared between all instances of that class. group chat for variables. iconic. ✨

πŸ‘€ quick note fr fr: this command is equivalent to the typevariable command provided by the snit package in tcllib β€” they're for approximately the same purpose. so if you've met snit before, you already know the vibe.

and one more lil thing: if you use it in a method defined directly on a class instance (like, through the oo::objdefine method definition), then classvariable is very much like just using this:

namespace upvar [namespace current] $var $var

…for each variable listed to classvariable. like, one of those per variable. yes, really. πŸŽ€


πŸ“ EXAMPLE πŸ“

this class counts how many instances of it have been made. counting era, we love her πŸ‘‘

oo::class create Counted {
    initialise {
        variable count 0
    }

    variable number
    constructor {} {
        classvariable count
        set number [incr count]
    }

    method report {} {
        classvariable count
        puts "This is instance $number of $count"
    }
}

set a [Counted new]
set b [Counted new]
$a report
        β†’ This is instance 1 of 2
set c [Counted new]
$b report
        β†’ This is instance 2 of 3
$c report
        β†’ This is instance 3 of 3

not the count going 1, 2, 3 and every instance knowing about it 😭 the shared class variable is doing ALL the work and it's serving fr fr.


🌈 SEE ALSO 🌈


πŸ’œ KEYWORDS πŸ’œ

class, class variable, variable


and that's the whole page, bestie!! go forth and share your variables across every instance, you absolute main character 🧚⭐

mwah πŸ’‹ β€” this was the TclOO manual, version 0.3, page classvariable(3tcl). periodt. πŸ’…

πŸ“¦ where this page comes from