nx::Class(3nx)
π nx::Class(3nx) β NX API π
πΈ NAME πΈ
nx::Class β API reference of the base-metaclass of the NX objectsystem. no cap, bestie. π
β¨ SYNOPSIS β¨
nx::Class create cls ?-superclasses superClassNames? ?-mixins mixinSpec?
?-filters filterSpec? ?option value ...? ?initBlock?
nx::Class new ?-superclasses superClassNames? ?-mixins mixinSpec?
?-filters filterSpec? ?initBlock?
cls ?public | private | protected? alias ?-debug? ?-deprecated?
methodName ?-returns valueChecker? ?-frame object | method? cmdName
cls create instanceName ?option value option value ...?
cls delete feature arg
cls filters submethod ?arg ...?
cls ?public | protected | private? forward ?-debug? ?-deprecated?
methodName ?-prefix prefixName? ?-frame object? ?-returns valueChecker?
?-verbose? ?target? ?arg ...?
cls info heritage ?pattern?
cls info instances ?-closure? ?pattern?
cls info mixinof ?-closure? ?-scope option? ?pattern?
cls info subclasses ?-closure? ?-dependent? ?pattern?
cls info superclasses ?-closure? ?pattern?
cls info info ?-asList?
cls info filters ?-guards? ?pattern?
cls info method option methodName
cls info methods ?-callprotection level? ?-type methodType? ?-path?
?namePattern?
cls info mixins ?-guards? ?pattern?
cls info slots ?-type className? ?pattern?
cls info variables ?pattern?
cls ?public | protected | private? method ?-debug? ?-deprecated? name
parameters ?-checkalways? ?-returns valueChecker? body
cls mixins submethod ?arg ...?
cls new ?-childof parentName? ?option value option value ...?
cls property ?-accessor public | protected | private? ?-class className?
?-configurable trueFalse? ?-incremental? ?-trace set | get | default?
spec ?initBlock?
cls require ?public | protected | private? method methodName
cls variable ?-accessor public | protected | private? ?-incremental?
?-class className? ?-configurable trueFalse? ?-initblock ?-trace set |
get | default? script? spec ?defaultValue?
π¦ DESCRIPTION π¦
okay so nx::Class is the base metaclass of the NX object system. all classes (e.g. cls) are direct or indirect instances of nx::Class. therefore, the methods provided by nx::Class are available to all classes. periodt.
a class cls which does not have nx::Class as its direct or indirect superclass is referred to as an application class. by default, when instantiating a new class from nx::Class, it becomes an application class with nx::Object being set as its superclass. a class cls which is explicitly declared as a direct or indirect subclass of nx::Class is referred to as a metaclass, that is, its instances will become classes as well. in other words, a metaclass instantiates and subclasses nx::Class at the same time. iconic. π
+---------+
| ::nx::* |
+---------+--------------------------------------Y
| |
| instance of |
| .-------. |
| +--------'+ instance of +----------+ |
| | |<....................| | |
| | Class | | Object | |
| | |....................>| | |
| +---------+ subclass of +-----+----+ |
| ^ ^ ^ |
\...|...|................................|......./
| | |
| |subclass.....(xor)......subclass|
| |of +-----------+ of|
| |.........| |..........|
| (metaclass) | /cls/ | (application class)
|.............| |
instance of +-----------+
classes can be created in the following ways:
nx::Class create cls ?-superclasses superClassNames? ?-mixins mixinSpec? ?-filters filterSpec? ?option value ...? ?initBlock?β to create a class having the explicit namecls, usecreate.nx::Class new ?-superclasses superClassNames? ?-mixins mixinSpec? ?-filters filterSpec? ?initBlock?β to create a class having an automatically assigned, implicit name, usenew.
the configuration options for direct and indirect instances of nx::Class, which can be passed when calling create and new, are documented in the subsequent section. iykyk. π
π CONFIGURATION OPTIONS FOR INSTANCES OF NX::CLASS π
configuration options can be used for configuring objects during their creation by passing the options as non-positional arguments into calls of new and create (see nx::Class). an existing object can be queried for its current configuration using cget and it can be re-configured using configure.
-superclasses ?superClassNames?β ifsuperClassNamesis not specified, returns the superclasses of the class. if provided, the class becomes the subclass ofsuperClassNames.-filters ?filterSpecs?β retrieves the list of filter methods currently active on instances of the class, iffilterSpecsis not set. otherwise, activates a list of filter methods for the instances of the class. filters are returned or set in terms of a list of filter specifications.-mixins ?mixinSpecs?β returns the list of mixin classes currently active on instances of the class, ifmixinSpecsis not specified. otherwise, the class is extended by the list of mixin classes provided bymixinSpecs. mixin classes are returned or set in terms of a list of mixin specifications.
the configuration options provided by nx::Object are equally available because an application class cls is an indirect instance of nx::Object. slay. β¨
π METHODS FOR INSTANCES OF NX::CLASS π
π«Ά alias π«Ά
cls ?public | private | protected? alias ?-debug? ?-deprecated?
methodName ?-returns valueChecker? ?-frame object | method? cmdName
define an alias method for the given class. the resulting method registers a pre-existing Tcl command cmdName under the (alias) name methodName with the class. if cmdName refers to another method, the corresponding argument should be a valid method handle. if it's a Tcl command (e.g., a proc), the argument should be a fully qualified Tcl command name. if you're aliasing a subcommand (e.g., array exists) of a Tcl namespace ensemble (e.g., array), cmdName must hold the fully qualified subcommand name (and not the ensemble name of the subcommand). no cap. π
as for a regular class method, -returns allows for setting a value checker on the values returned by the aliased command cmdName.
when creating an alias method for a C-implemented Tcl command (i.e., a command defined using the Tcl/NX C-API), -frame sets the scope for variable references used in the aliased command. if the provided value is object, then variable references will be resolved in the context of the called object, i.e., the object upon which the alias method is invoked, as if they were object variables. there is no need for using the colon-prefix notation for identifying object variables. if the value is method, then the aliased command will be executed as a regular method call. the command is aware of its called-object context; i.e., it can resolve ::nx::self. in addition, the alias method has access to the method-call context (e.g., nx::next). if -frame is omitted, and by default, the variable references will resolve in the context of the caller of the alias method.
to express deprecation of the alias method methodName, set the -deprecated flag. deprecated methods remain usable from client code, but their usage will be signaled to the developer and/or can be tracked using ::nsf::deprecated. to register methodName with the debugger, set the -debug flag. entering and exiting a method, which was flagged for debugging, is recorded by calling the redefinable callback procs ::nsf::debug::call and ::nsf::debug::exit, respectively. by default, these callbacks forward to ::nsf::log, which can also be customized at the script level.
π§ __class_configureparameter π§
cls __class_configureparameter
computes and returns the configuration options available for cls instances, to be consumed as method-parameter specification by configure. so useful. β¨
π create π
cls create instanceName ?option value option value ...?
this factory method creates an instance instanceName of cls and returns instanceName.
% nx::Class create AClass {
:method init args {
next
}; # initialization method for instances of 'AClass'
}; # defines a class 'AClass' being an instance of 'nx::Class'
::AClass
% ::AClass create anInstance; # defines an object 'anInstance' being an instance of 'AClass'
::anInstance
% ::anInstance info class
::AClass
% ::AClass info class
::nx::Class
create accepts the configuration options option available for this instance, such as those defined by properties of cls (see property).
note that create is called internally when defining an instance of cls using new.
by calling create on nx::Class itself, the created instance will become a new application class instanceName on which create can also be applied (i.e., it can be instantiated). if the so-created class has ::nx::Class its direct or indirect superclass, instanceName is referred to as a metaclass; that is, a class whose instances are again classes. main character energy. π
π delete π
cls delete feature arg
this method serves as the equivalent to Tcl's rename for removing structural (properties, variables) and behavioral features (methods) of the class:
ποΈ delete
cls delete property propertyName
cls delete variable variableName
cls delete method methodName
Okay so delete is the "we don't talk about that anymore" button π β it removes a property propertyName, a variable variableName, and a method methodName, respectively, that were previously defined for the scope of the class. Not a global purge, bestie, just the class-scope stuff.
And delete method is lowkey versatile: it works equally well for removing regular methods (see method), alias methods (see alias), and forwarder methods (see forward). One deleter to rule them all, no cap π«Ά
ποΈ filters
cls filters submethod ?arg ...?
This is where you go to access and modify the list of methods which are registered as filters with cls, using a specific setter or getter submethod. Filter girl summer πΈ Let's meet the submethods:
cls filters add spec ?index?
Inserts a single filter into the current list of filters of cls. If you pass index, you get to pick the position in the existing list of filters where the new one lands. Omit it and index defaults to the list head (0) β i.e. front of the line, main character energy π
cls filters clear
Removes all filters from cls and hands you back the list of removed filters. And just so you know: clearing is exactly equivalent to passing an empty list for filterSpecList to class filter set. Same vibe, different door.
cls filters delete ?-nocomplain? specPattern
Removes a single filter from the current list of filters of cls whose spec matches specPattern. specPattern can contain special matching chars (see string match). Heads up though: class filters delete will throw an error if there's no matching filter β unless -nocomplain is set. Then it's chill about it π
cls filters get
Returns the list of current filter specifications registered for cls. The receipts, basically π§Ύ
cls filters guard methodName ?expr?
If expr is specified, this registers a guard expression expr with a filter methodName. This requires that the filter methodName has been previously set using filters set or added using filters add. expr must be a valid Tcl expression (see expr). And an empty string for expr will clear the currently registered guard expression for filter methodName.
If expr is omitted, you get back the guard expression set on the filter methodName defined for cls. If none is available, an empty string will be returned. No guard, no drama.
cls filters methods ?pattern?
Omit pattern and you get all filter names which are defined by cls. Pass pattern and the returned filters get limited to those whose names match patterns (see string match). Filtered filters, very meta β¨
cls filters set filterSpecList
filterSpecList takes a list of filter specs, where each spec is itself either a one-element or a two-element list: methodName ?-guard guardExpr?. methodName identifies an existing method of cls which becomes registered as a filter. If a spec has three elements, the third element guardExpr will be stored as a guard expression of the filter. This guard expression must be a valid Tcl expression (see expr). expr is evaluated when cls receives a message, to determine whether the filter should intercept the message. Guard expressions are how you realize context-dependent or conditional filter composition β iykyk π¦
Every methodName in a spec must resolve to an existing method in the scope of the class. That's not optional, bestie. To access and to manipulate the list of filters ofcls,cget|configure -filterscan also be used.
π forward
cls ?public | protected | private? forward ?-debug? ?-deprecated? methodName ?-prefix prefixName? ?-frame object? ?-returns valueChecker? ?-verbose? ?target? ?arg ...?
Define a forward method for the given class, bestie. Here's the tea: defining a forward method registers a predefined, but changeable list of forwarder arguments under the (forwarder) name methodName. When you call the forward method, those forwarder arguments get evaluated as a Tcl command call. So if it's present, target is interpreted as a Tcl command (e.g., a Tcl proc or an object) and the remainder of the forwarder arguments arg are passed into this command as arguments. The actual method arguments from the invocation of the forward method itself get appended to the list of forwarder arguments. Simple as that π
If target is omitted, the value of methodName is implicitly set and used as target. That means: when you hand over a fully-qualified Tcl command name as methodName with no target, the unqualified methodName (namespace tail) becomes the forwarder name, while the fully-qualified one serves as the target. Two jobs, one name, iconic β¨
Just like a regular method, -returns lets you set a value checker on the values returned by the resulting Tcl command call. And when you pass object to -frame, the resulting Tcl command is evaluated in the context of the object receiving the forward method call. That way, variable names used in the resulting execution of a command become resolved as object variables. Sneaky and powerful, we love her π«Ά
To express deprecation of the forward method methodName, set the -deprecated flag. Deprecated methods remain usable from client code, but their usage will be signaled to the developer and/or can be tracked using ::nsf::deprecated. To register methodName with the debugger, set the -debug flag. Entering and exiting a method which was flagged for debugging is recorded by calling the redefinable callback procs ::nsf::debug::call and ::nsf::debug::exit, respectively. By default, these callbacks forward to ::nsf::log, which can also be customized at the script level. Debug girlies stay winning π₯
The list of forwarder arguments arg can contain, as its elements, a mix of literal values and placeholders. Placeholders are prefixed with a percent symbol (%) and substituted for concrete values upon calling the forward method. They're how you construct and manipulate the arguments passed into the resulting command call on the fly:
%methodbecomes substituted for the name of the forward method, i.e. methodName.%selfbecomes substituted for the name of the object receiving the call of the forward method.%1becomes substituted for the first method argument passed to the call of the forward method. This requires, in turn, that at least one argument is passed along with the method call.
Alternatively, %1 accepts an optional argument defaults: {%1 defaults}. defaults must be a valid Tcl list of two elements. For the first element, %1 is substituted when there is no first method argument which can be consumed by %1. The second element is inserted upon availability of a first method argument, with the consumed argument being appended right after the second list element. This placeholder is typically used to define a pair of getter/setter methods. So cute, so useful π
{%@index value}becomes substituted for the specified value at position index in the forwarder-arguments list, with index being either a positive integer, a negative integer, or the literal valueend(such as in Tcl'slindex). Positive integers specify a list position relative to the list head; negative integers give a position relative to the list tail. Indexes for positioning placeholders in the definition of a forward method are evaluated from left to right and should be used in ascending order.
Note that value can be a literal or any of the placeholders (e.g., %method, %self). Position prefixes are exempted β they are evaluated as %cmdName-placeholders in this context.
{%argclindex list}becomes substituted for the nth element of the provided list, with n corresponding to the number of method arguments passed to the forward method call.%%is substituted for a single, literal percent symbol (%).%cmdNameis substituted for the value returned from executing the Tcl command cmdName. To pass arguments to cmdName, the placeholder should be wrapped into a Tcl list:{%cmdName ?arg ...?}.
Consider using fully-qualified Tcl command names for cmdName to avoid possible name conflicts with the predefined placeholders, e.g., %self vs. %::nx::self. Learn from our near-misses bestie π
To disambiguate the names of subcommands or methods which potentially become called by a forward method, a prefix prefixName can be set using -prefix. This prefix is prepended automatically to the argument following target (i.e., a second argument), if present. If it's missing, -prefix has no effect on the forward method call. No argument, no prefix, no problem π
ngl bestie, if you wanna snoop on exactly what those placeholders up there are cooking, just flip on the -verbose switch and the command list that's about to be executed (i.e., after substitution, so you see the real deal) gets printed using ::nsf::log at debugging level notice, right at the moment the forward method gets called. πβ¨
π info π
Okay so info is the whole backstage-pass situation: a collection of introspection submethods covering the structural features (think configuration options, superclasses, that whole vibe) and the behavioral features (methods, filters, etc.) that cls provides to its instances. It's giving VIP tour of the class. π
cls info heritage ?pattern?
Leave pattern out and you get the list of object names of all the direct and indirect superclasses and per-class mixin classes of cls, listed in their order of precedence β the ones that are active for instances of cls. Pass pattern and only superclasses and mixin classes whose names match pattern get listed (see string match). πΈ
cls info instances ?-closure? ?pattern?
No pattern? Then you get a list of the object names of every direct instance of cls. Set the -closure switch and indirect instances come along for the ride too. A direct instance is one you made by using create or new on cls; an indirect instance was created from a direct or indirect subclass of cls. Pass pattern and only instances whose names match pattern are listed (see string match). π
cls info mixinof ?-closure? ?-scope option? ?pattern?
No pattern? You get the object names of every object for which cls is active as a direct mixin class. Set -closure and objects that have cls as an indirect mixin class show up too. Pass pattern and only objects whose names match pattern are listed (see string match). The valid values for option are all, object, and class:
objectβ only objects that haveclsas a per-object mixin class get returned. πclassβ only classes that haveclsas a per-class mixin class get returned.all(the default) β both of those end up in the returned list. π
cls info subclasses ?-closure? ?-dependent? ?pattern?
No pattern? You get the object names of the direct subclasses of cls. Set -closure and indirect subclasses are returned as well. Turn on -dependent and indirect subclasses introduced by mixin class relations of subclasses of cls are reported too. Heads up: -closure and -dependent are mutually exclusive, so pick a lane bestie. Pass pattern and only subclasses whose names match pattern are listed (see string match). π
cls info superclasses ?-closure? ?pattern?
No pattern? You get the object names of all direct superclasses of cls. Set -closure and indirect superclasses come back too. Pass pattern and only superclasses whose names match pattern are listed (see string match). β
cls info info ?-asList?
Returns the available submethods of the info method ensemble for cls β either as a pretty-printed string, or as a Tcl list if you set the -asList switch, in case you wanna keep processing it. π«Ά
cls info filters ?-guards? ?pattern?
Omit pattern and you get all filter names defined by cls. Turn on -guards and the corresponding guard expressions, if there are any, get reported alongside each filter as a three-element list: filterName -guard guardExpr. Specify pattern and the returned filters get limited to those whose names match pattern (see string match). π
cls info method option methodName
This introspection submethod is your access point to the details of methodName provided by cls. If methodName isn't the name of an existing method, an empty string comes back. And since an empty string can be a legit return value, if you need to tell "no such method" apart from "empty string, but valid" (e.g., for info method args|parameters|args|...), use info method exists. iykyk. π
Permitted values for option are:
argsβ returns a list containing the parameter names ofmethodName, in order of the method-parameter specification. πbodyβ returns the body script ofmethodName.callprotectionβ returns the call-protection level set formethodName; possible values:public,protected,private.debugβ returns1ifmethodNameis in debug mode,0otherwise.definitionβ returns a canonical command list which allows for (re-)definingmethodName.definitionhandleβ returns the method handle for a submethod in a method ensemble, from the perspective ofclsas method provider.methodNamemust contain a complete method path.deprecatedβ returns1ifmethodNameis deprecated,0otherwise.existsβ returns1if there is amethodNameprovided bycls, returns0otherwise.handleβ returns the method handle formethodName.originβ returns the aliased command ifmethodNameis an alias method, or an empty string otherwise.parametersβ returns the parameter specification ofmethodNameas a list of parameter names and type specifications.registrationhandleβ returns the method handle for a submethod in a method ensemble from the perspective of the method caller.methodNamemust contain a complete method path.returnsβ gives the type specification defined for the return value ofmethodName.submethodsβ returns the names of all submethods ofmethodName, ifmethodNameis a method ensemble. Otherwise, an empty string is returned.syntaxβ returns the method parameters ofmethodNameas a concrete-syntax description, to be used in human-understandable messages (e.g., errors or warnings, documentation strings).typeβ returns whethermethodNameis a scripted method, an alias method, a forwarder method, or a setter method. π
cls info methods ?-callprotection level? ?-type methodType? ?-path? ?namePattern?
Returns the names of all methods defined by cls β and yes, methods defined using alias and forward are covered too. The returned methods can be limited to those whose names match namePattern (see string match).
Set -callprotection and only methods of a certain call protection level (public, protected, or private) come back. Want a specific flavor? Request it with -type. The recognized values for methodType are:
scriptedβ denotes methods defined usingclass method; β¨aliasβ denotes alias methods defined usingclass alias;forwarderβ denotes forwarder methods defined usingclass forward;setterβ denotes methods defined using::nsf::setter;allβ returns methods of any type, no restrictions (also the default value); π
cls info mixins ?-guards? ?pattern?
Omit pattern and you get the object names of the mixin classes which extend cls directly. Turn on -guards and the corresponding guard expressions, if any, are reported along with each mixin as a three-element list: className -guard guardExpr. The returned mixin classes can be limited to those whose names match pattern (see string match). π¦
cls info slots ?-type className? ?pattern?
No pattern? You get the object names of all slot objects defined by cls. The returned slot objects can be limited according to any one, or a combination, of these criteria: first, slot objects can be filtered based on their command names matching pattern (see string match). Second, -type lets you select slot objects which are instantiated from a subclass className of nx::Slot (default: nx::Slot). π
cls info variables ?pattern?
Omit pattern and you get the object names of all slot objects provided by cls which are responsible for managing properties and variables of cls. Otherwise, only slot objects whose names match pattern come back.
This is equivalent to calling:
cls info slots -type ::nx::VariableSlot pattern
To extract details of each slot object, use the info submethods available for each slot object. π§
π method π
cls ?public | protected | private? method ?-debug? ?-deprecated? name parameters ?-checkalways? ?-returns valueChecker? body
Defines a scripted method methodName for the scope of the class. The method becomes part of the class's signature interface. Besides a methodName, the method definition specifies the method parameters and a method body. Slay, that's the whole shape of it. π₯
parameters takes a Tcl list, and that list can hold literally any number of non-positional and positional parameter definitions β no cap, go off π
. Every single parameter definition is made of three things: a parameter name, a parameter-specific value checker, and parameter options.
The body is where the actual method implementation lives, as a script block. Inside that body script you get the colon-prefix notation to mean an object variable and a self call, bestie, it's giving main character energy β¨. On top of that, the context of the object receiving the method call (that's the message, iykyk) can be accessed β like with nx::self β and the call stack can be introspected, e.g. using nx::current π
Optionally, -returns lets you set a value checker on the values your method implementation hands back π. And if you flip the -checkalways switch, value checking on arguments and on the return value is guaranteed to happen, even if value checking is temporarily disabled; see nx::configure.
Wanna express that a method name is deprecated? Set the -deprecated flag. Deprecated methods stay usable from client code, no cap, but their usage gets signaled to the developer and/or can be tracked using ::nsf::deprecated π«Ά. Wanna register the name with the debugger? Set the -debug flag. Entering and exiting a method that was flagged for debugging gets recorded by calling the redefinable callback procs ::nsf::debug::call and ::nsf::debug::exit, respectively. By default those callbacks forward to ::nsf::log, which you can also customize at the script level πΈ.
A method closely resembles a Tcl proc, but lowkey it differs in some important ways:
- First, a method can define non-positional parameters and value checkers on arguments.
- Second, the script implementing the method body can contain object-specific notation and commands (see above).
- Third, method calls cannot be intercepted using Tcl trace π.
Note that an existing Tcl proc can be registered as an alias method with the class (see alias).
mixins
cls mixins submethod ?arg ...?
Accesses and modifies the list of mixin classes of cls using a specific setter or getter submethod π¦:
cls mixins add spec ?index?β Inserts a single mixin class into the current list of mixin classes ofcls. Usingindex, you can set a position in the existing list of mixin classes for inserting the new mixin class. If omitted,indexdefaults to the list head (0).cls mixins classes ?pattern?β Ifpatternis omitted, returns the object names of the mixin classes which extendclsdirectly. By specifyingpattern, the returned mixin classes can be limited to those whose names matchpattern(seestring match).cls mixins clearβ Removes all mixin classes fromclsand returns the list of removed mixin classes. Clearing is equivalent to passing an empty list formixinSpecListtomixins set.cls mixins delete ?-nocomplain? specPatternβ Removes a mixin class from a current list of mixin classes ofclswhose spec matchesspecPattern.specPatterncan contain special matching chars (seestring match).class mixins deletewill throw an error if there is no matching mixin class, unless-nocomplainis set π.cls mixins getβ Returns the list of current mixin specifications.cls mixins guard className ?expr?β Ifexpris specified, a guard expressionexpris registered with the mixin classclassName. This requires that the corresponding mixin classclassNamehas been previously set usingclass mixins setor added usingmixins add.exprmust be a valid Tcl expression (seeexpr). An empty string forexprwill clear the currently registered guard expression for the mixin classclassName.
If expr is not specified, returns the active guard expression. If none is available, an empty string will be returned.
cls mixins set mixinSpecListβmixinSpecListrepresents a list of mixin class specs, with each spec being itself either a one-element or a three-element list:className ?-guard guardExpr?. If having one element, the element will be considered theclassNameof the mixin class. If having three elements, the third elementguardExprwill be stored as a guard expression of the mixin class. This guard expression will be evaluated usingexprwhenclsreceives a message to determine if the mixin is to be considered during method dispatch or not. Guard expressions allow for realizing context-dependent or conditional mixin composition β¨.
At the time of setting the mixin relation β that is, calling mixins β every className as part of a spec must be an existing instance of nx::Class. To access and to manipulate the list of mixin classes of cls, cget|configure -mixins can also be used.
new
cls new ?-childof parentName? ?option value option value ...?
A factory method to create autonamed instances of cls π. It returns the name of the newly created instance. For example:
% nx::Class create AClass; # defines a class 'AClass' being an instance of 'nx::Class'
::AClass
% set inst [::AClass new]; # defines an autonamed object being an instance of 'AClass'
::nsf::__#0
% $inst info class
::AClass
The factory method will provide computed object names of the form, e.g. ::nsf::__#0. The uniqueness of generated object names is guaranteed for the scope of the current Tcl interpreter only π.
It is a frontend to create which will be called by new once the name of the instance has been computed, passing along the arguments option to new as the configuration options (see create).
If -childof is provided, the new object will be created as a nested object of parentName. parentName can be the name of either an existing NX object or an existing Tcl namespace. If non-existing, a Tcl namespace parentName will be created on the fly π§.
property
cls property ?-accessor public | protected | private? ?-class className? ?-configurable trueFalse? ?-incremental? ?-trace set | get | default? spec ?initBlock?
Defines a property for the scope of the class π. The spec provides the property specification as a list holding at least one element or, maximum, two elements: propertyName?:typeSpec? ?defaultValue?. The propertyName is also used to form the names of the getter/setter methods, if requested (see -accessor). It is, optionally, equipped with a typeSpec following a colon delimiter which specifies a value checker for the values which become assigned to the property. The second, optional element sets a defaultValue for this property.
If -accessor is set, a property will provide for different getter and setter methods π:
obj propertyName existsβ Returns1if the value store ofpropertyName(e.g., an object variable) exists and has been given a value, returns0otherwise.obj propertyName set valueβ Sets the propertypropertyNametovalue.obj propertyName getβ Returns the current value of propertypropertyName.obj propertyName unsetβ Removes the value store ofpropertyName(e.g., an object variable), if existing.
The option value passed along -accessor sets the level of call protection for the generated getter and setter methods: public, protected, or private. By default, no getter and setter methods are created π.
Turning on the switch -incremental provides a refined setter interface to the value managed by the property. First, setting -incremental implies requesting -accessor (set to public by default, if not specified explicitly). Second, the managed value will be considered a valid Tcl list. A multiplicity of 1..* is set by default, if not specified explicitly as part of spec. Third, to manage this list value element-wise (incrementally), two additional setter methods become available π₯:
obj propertyName add element ?index?β Addingelementto the managed list value, at the list position given byindex(by default:0).obj propertyName delete ?-nocomplain? elementPatternβ Removing the first occurrence of an element from the managed list value which matcheselementPattern.elementPatterncan contain matching characters (seestring match). An error will be thrown if there is no match, unless-nocomplainis set.
okay so real talk about -configurable, bestie π
When you set -configurable to true (which, btw, is the default), the property can be accessed and modified through cget and configure, respectively. If it's false, then no configuration option will become available via cget and configure. Like, none. Zero. Gone. π
And if neither -accessor nor -configurable are requested? Then the value managed by the property will have to be accessed and modified directly. If the property manages an object variable, its value will be readable and writable using set and eval. Lowkey feral but okay π
The -trace option causes certain slot methods to be executed whenever get, set, or default operations are invoked on the property:
set:slot value=set obj propertyName valueget:slot value=get obj propertyNamedefault:slot value=default obj propertyName
A property becomes implemented by a slot object under any of the following conditions β get into it β¨
-configurableequals true (by default).-accessoris one ofpublic,protected, orprivate.-incrementalis turned on.initBlockis a non-empty string.
Assuming default settings, every property is realized by a slot object π«Ά
Provided a slot object managing the property is to be created, a custom class className from which this slot object is to be instantiated can be set using -class. The default value is ::nx::VariableSlot.
The last argument initBlock accepts an optional Tcl script which is passed into the initialization procedure (see configure) of the property's slot object. See also initBlock for create and new. iykyk π§
πΈ require πΈ
cls require ?public | protected | private? method methodName
Attempts to register a method definition made available using ::nsf::method::provide under the name methodName with cls. The registered method is subjected to default call protection (protected), if not set explicitly. Protecting its peace fr fr π‘οΈ
π variable π
cls variable ?-accessor public | protected | private?
?-incremental? ?-class className? ?-configurable trueFalse?
?-initblock ?-trace set | get | default? script? spec
?defaultValue?
Defines a variable for the scope of the class. The spec provides the variable specification: variableName?:typeSpec?. The variableName will be used to name the underlying Tcl variable and the getter/setter methods, if requested (see -accessor). spec is optionally equipped with a typeSpec following a colon delimiter which specifies a value checker for the values managed by the variable. Optionally, a defaultValue can be defined. The main character gets options, periodt π
If -accessor is set explicitly, a variable will provide for getter and setter methods:
obj variableName existsβ Returns 1 if the value store of variableName (e.g., an object variable) exists and has been given a value, returns 0 otherwise. Like a lil vibe check on whether it's even there π΅οΈobj variableName set varValueβ Sets variableName to varValue.obj variableName getβ Returns the current value of variableName.obj variableName unsetβ Removes variableName, if existing, underlying the property.
The option value passed along -accessor sets the level of call protection for the getter and setter methods: public, protected, or private. By default, no getter and setter methods are created. π«
Turning on the switch -incremental provides a refined setter interface to the value managed by the variable. First, setting -incremental implies requesting -accessor (public by default, if not specified explicitly). Second, the managed value will be considered a valid Tcl list. A multiplicity of 1..* is set by default, if not specified explicitly as part of spec (see above). Third, to manage this list value element-wise (incrementally), two additional setter operations become available:
obj variableName add element ?index?β Adding element to the managed list value, at the list position given by index (by default: 0).obj variableName delete ?-nocomplain? elementPatternβ Removing the first occurrence of an element from the managed list value which matches elementPattern. elementPattern can contain matching characters (seestring match). An error will be thrown if there is no match, unless-nocomplainis set. No match, no mercy π
By setting -configurable to true, the variable can be accessed and modified via cget and configure, respectively. If false (the default), the interface based on cget and configure will not become available. In this case, and provided that -accessor is set, the variable can be accessed and modified via the getter/setter methods. Alternatively, the underlying Tcl variable, which is represented by the variable, can always be accessed and modified directly, e.g., using eval. By default, -configurable is false. Note the switch-up from properties btw β properties default to true, variables default to false π
The -trace option causes certain slot methods to be executed whenever get, set, or default operations are invoked on the variable:
set:slot value=set obj variableName valueget:slot value=get obj variableNamedefault:slot value=default obj variableName
A variable becomes implemented by a slot object under any of the following conditions:
-configurableequals true.-accessoris one ofpublic,protected, orprivate.-incrementalis turned on.-initblockis a non-empty string.
Provided a slot object managing the variable is to be created, a custom class className from which this slot object is to be instantiated can be set using -class. The default value is ::nx::VariableSlot.
Using -initblock, an optional Tcl script can be defined which becomes passed into the initialization procedure (see configure) of the variable's slot object. See also initBlock for create and new. π
β¨ OBJECT LIFE CYCLE β¨
okay bestie, this is the β¨main character arcβ¨ of every NX object β the whole journey from before it's born to after it's gone. nx::Class hands you the levers to control the important stages an NX object passes through, between and including its creation and its destruction: allocation, recreation, deallocation. periodt. π
/cls/->create(/instance/)
.---------------. exists? [false] .----------------. .-------------------.
---->|Class::create()|----><>---------------->|Class::__alloc()|-----------><>---->|Object::configure()|
`---------------' | (1) `----------------' ^ (3) `---------+---------'
[true] | | | (4)
| .-------------------. | .------------------.
`->|Class::__recreate()|-------------------------' |/instance/->init()|
(2) `-------------------' `------------------'
/instance/->destroy()
.-----------------. .------------------.
---->|Object::destroy()|---->|Class::__dealloc()|
`-----------------' (5) `------------------'
Object creation is controlled by the factory method create, which nx::Class provides to its instance cls. create produces a new object instance as an instance of cls, in a number of steps:
[1]β if instance does not represent an existing object, an internal call to__alloc, provided bynx::Class, runs the allocation procedure for a fresh instance of cls.[2]β if instance corresponds to an existing object, the recreation procedure gets triggered by calling__recreate, defined bynx::Class.[3]β the newly allocated or recreated object instance then gets configured by dispatchingconfigure, provided bynx::Object, which consumes the configuration options passed intocreate. This establishes the instance's initial state β e.g. by setting object variables and object relations according to the configuration options and their corresponding default values. β¨[4]β finally, the initialization methodinitis dispatched, if it's available for instance.initcan be defined by cls on behalf of its instance instance, e.g. to lay out a class-specific initialization behavior. π
% nx::Class create Foo {:property x}
% Foo method init {} {set :y [expr {${:x} + 1}]}
% Foo public method bar {} {return ${:y}}
% Foo create f1 -x 101
% f1 cget -x
101
% f1 bar
102
Alternatively, the object instance may define a per-object init all on its own. A per-object init can be chained to a class-level init using nx::next, just like a regular method. π¦
Note that the definition of aninitmethod must contain an empty parameter specification, sinceinitis always called with an empty argument list. (no cap, it just is π«Ά)
Object destruction, like the kind triggered by an application-level destroy call (5), is finalized by __dealloc, offered by nx::Class.
In the following, the three built-in procedures β allocation, recreation, and deallocation β are explained:
- Allocation:
__alloccreates a blank object instance as an instance of cls and returns the fully-qualified instance.__allocis primarily used internally bycreate, to allocate a Tcl memory storage for instance and to register instance with the Tcl interpreter as a new command. π - Recreation: Recreation is the NX scheme for resolving naming conflicts between objects: an object is requested to be created using
createornewwhile an object of an identical object name, e.g. instance, already exists:
% Object create Bar
::Bar
% Object create Bar; # calls Object->__recreate(::Bar, ...)
::Bar
In such a situation, the built-in __recreate first unsets the object state (i.e., Tcl variables held by the object) and removes relations of the object under recreation with other objects. Then, second, standard object initialization is performed by calling configure and init, if any. πΈ
Alternatively, recreation will be performed as a sequence of destroy and create calls in the following recreation scenarios:
- An existing class is requested to be recreated as an object.
- An existing object is requested to be recreated as a class.
% Object create Bar
::Bar
% Class create Bar; # calls Bar->destroy() & Class::create(::Bar, ...)
- An object of an object system other than NX (e.g. XOTcl2) is asked to be recreated.
- Deallocation:
__deallocmarks an instance instance of cls for deletion by returning its Tcl memory representation to the Tcl memory pool and by unregistering the corresponding Tcl command with the Tcl interpreter. π
Beware that __dealloc does not necessarily cause the object to be deleted immediately. Depending on the lifecycle of the object's environment (e.g. the Tcl interp interpreter, the containing namespace) and on call references down the callstack, the actual memory freeing/returning operation may occur at a later point. π
The three methods __alloc, __recreate, and __dealloc are internally provided and internally called. By default they are not part of the method interface of cls, and they cannot be called directly by clients of cls. On top of that, __alloc, __recreate, and __dealloc are protected from redefinition by a script. π₯
To extend or to replace the built-in allocation, recreation, and deallocation procedure, the methods __alloc, __recreate, and __dealloc can be refined by providing a custom method implementation:
- as a per-object method of cls;
- as a method of a per-object mixin class extending cls;
- as a method of a per-class mixin class extending
nx::Class; - as a method of a subclass specializing
nx::Class, from which cls is to be instantiated.
This custom implementation can redirect to the built-in __alloc, __recreate, and __dealloc, respectively, by using nx::next. By providing such a custom implementation, __alloc, __recreate, and __dealloc, respectively, become available as callable methods of cls: π
cls __alloc instance
cls __recreate instance ?arg ...?
cls __dealloc instance
π COPYRIGHT π
Copyright (c) 2014-2019 Stefan Sobernig <stefan.sobernig@wu.ac.at>, Gustaf Neumann <gustaf.neumann@wu.ac.at>; available under the Creative Commons Attribution 3.0 Austria license (CC BY 3.0 AT).
and that's a wrap on the whole page, bestie!! πβ you just read the entire nx::Class(3nx) manual, source nx::Class, version 2.4.0 β literally iconic behavior from you, go forth and create some objects π
π«Άπ
π¦ where this page comes from
- debian trixie: nsf 2.4.0-1 Β· MIT
- ubuntu questing: nsf 2.4.0-1
- ubuntu resolute: nsf 2.4.0-1build1 Β· MIT
- ubuntu stonking: nsf 2.4.0-1build1 Β· MIT
- Copyright (c) 2014-2019 Stefan Sobernig <stefan\&.sobernig@wu\&.ac\&.at>, Gustaf Neumann <gustaf\&.neumann@wu\&.ac\&.at>; available under the Creative Commons Attribution 3\&.0 Austria license (CC BY 3\&.0 AT)\&
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms