Define a primitive data type: Difference between revisions

no edit summary
m (→‎{{header|Visual Basic .NET}}: lang tag (vb --- vbnet ?))
No edit summary
Line 627:
$t = 'xyzzy';
# dies, too small. string is 0 interpreted numerically</lang>
 
=={{header|Tcl}}==
Tcl allows the programmer to create traces, procedures that execute when variables are read/written/unset
<lang tcl>namespace eval ::myIntType {
variable value_cache
array set value_cache {}
variable type integer
variable min 1
variable max 10
variable errMsg "cannot set %s to %s: must be a $type between $min and $max"
}
proc ::myIntType::declare varname {
set ns [namespace current]
uplevel #0 [list trace add variable $varname write ${ns}::write]
uplevel #0 [list trace add variable $varname read ${ns}::read]
uplevel #0 [list trace add variable $varname unset ${ns}::unset_var]
}
proc ::myIntType::unset_var {varname args} {
variable value_cache
unset value_cache($varname)
}
proc ::myIntType::validate {value} {
variable type
variable min
variable max
expr {[string is $type -strict $value] && $min <= $value && $value <= $max}
}
proc ::myIntType::read {varname args} {
if {! [info exists $varname]} {
# variable is not yet set
return
}
variable value_cache
upvar #0 $varname var
if {[myIntType_validate $var]} {
set value_cache($varname) $var
}
}
proc ::myIntType::write {varname args} {
variable value_cache
upvar #0 $varname var
set value $var
if {[validate $value]} {
set value_cache($varname) $value
} else {
if {[info exists value_cache($varname)]} {
set var $value_cache($varname)
}
variable errMsg
error [format $errMsg $varname $value]
}
}</lang>
 
So, in an interactive tclsh we can see:
<pre>% myIntType::declare foo
% set foo ;# regular Tcl error: foo is declared but still unset
can't read "foo": no such variable
% set foo bar
can't set "foo": cannot set foo to bar: must be a integer between 1 and 10
% set foo 3
3
% incr foo 10
can't set "foo": cannot set foo to 13: must be a integer between 1 and 10
% incr foo -10
can't set "foo": cannot set foo to -7: must be a integer between 1 and 10
% set foo 0
can't set "foo": cannot set foo to 0: must be a integer between 1 and 10
% set foo
3
% set foo [expr {$foo * 1.5}]
can't set "foo": cannot set foo to 4.5: must be a integer between 1 and 10
% set foo
3
% unset foo
% </pre>
 
 
=={{header|Toka}}==
Anonymous user