STERNO - Examples
Here is a simple class and some code that uses it that demonstrates the basic
features of Sterno
package require Sterno
# Create a named class.
Sterno::defClass Colors {
field red ;# Define fields, but we didn't initialize them
field green
field blue
# Constructor which sets the fields.
method construct {r g b} {
set red $r
set green $g
set blue $b
}
# Normal method that returns another instance of this class.
method invert {} {
# Use class field to make it easy to change class name
return [$class new [expr 255-$red] [expr 255-$green] [expr 255-$blue]]
}
# A method with an argument
method add {num} {
set red [expr $red+$num]
set green [expr $green+$num]
set blue [expr $blue+$num]
}
# Always a useful method
method toString {} {
return "Red = $red, green = $green, blue = $blue"
}
}
#
# Sometimes its easier to add methods outside of the defClass
# body. Since method is just a class method, this is easy.
#
Colors method x11Color {} {
return [format "#%02X%02X%02X" $red $green $blue]
}
#
# Try if out.
#
puts "Trying out example code:"
set color1 [Colors new 10 2 30]
puts " Color 1 is [$color1 toString]"
puts " Color 1 in X11 format is [$color1 x11Color]"
set color2 [$color1 invert]
puts " Color 1 inverted is [$color2 toString]"
Colors delete ;# deletes class and all objects