This is a little OO system I'm using. Wanted something that would work across various EDA tools and versions (8.4/8.5/8.6) and without Itcl. Plus, I wanted composition and hierarchy to be "natural" just like nested namespaces. It does use the ugly "::" separator but some sugar could be added to remove that. I'm just moving from TCL noob to hack so I couldn't resist coming with with an amateur OO system. It's probably very similar to others I've seen on this site.
namespace eval gloo {
namespace eval VAULT {
variable GLOO_CODE {
proc new { name {cargs ""} } {
set calling_ns [uplevel namespace current]
set instname "$calling_ns\::$name"
if {$calling_ns == "::"} { set instname "::$name" }
set new_code "[set VAULT::GLOO_CODE]\n#==== CODE from : $instname ====#\n$cargs"
namespace eval $instname\::VAULT {}
set $instname\::VAULT::GLOO_CODE $new_code
namespace eval $instname $new_code
return $instname
}
}
}
eval [set VAULT::GLOO_CODE]
}
# Create a class
gloo::new Toaster {
variable crumbs 0
proc toast {nslices} {
puts -nonewline "[namespace current] is toasting $nslices slices"
variable crumbs
if {$crumbs > 50} {
error "== FIRE! FIRE! =="
}
set crumbs [expr $crumbs+4*$nslices]
puts " and made $crumbs crumbs"
}
proc clean {} {
variable crumbs
set crumbs 0
}
}
# Can call methods on the class
Toaster::toast 4
# Create an instance
Toaster::new ToasterInst
set ToasterInst::crumbs 3
ToasterInst::toast 6
ToasterInst::clean
# Extend a class.. Extending is the same as constructing, just that there's code
# passed to the constructor to tack onto the class
Toaster::new SmartToaster {
rename toast super-toast
proc toast {nslices} {
variable crumbs
if {$crumbs > 40} {
clean
}
return [super-toast $nslices]
}
}
SmartToaster::toast 6
SmartToaster::new SmartInst
SmartInst::toast 7
# Hierarchy is natural...
gloo::new ToastMaster {
Toaster::new foo
SmartToaster::new bar
proc toast {slices} {
foreach c [namespace children [namespace current]] {
catch {eval $c\::toast $slices}
}
}
}
ToastMaster::foo::toast 5
ToastMaster::bar::toast 6
ToastMaster::toast 1