Posted to tcl by sebres at Wed Mar 03 21:01:49 GMT 2021view pretty

proc __on_set_check { condition _this n2 op } {
  upvar $_this this
  if $condition {} else { return -level 2 -code error "variable $_this set to invalid value [list $this]" }
}

proc __typed { _ref condition } {
  upvar $_ref ref
  trace add variable ref write [list __on_set_check $condition]
}

proc int {_var args} {
  upvar $_var var
  __typed var {[string is integer -strict $this]}
  if {[llength $args]} { set var {*}$args }
}

proc int? {_var args} {
  upvar $_var var
  __typed var {[string is integer $this]}
  if {[llength $args]} { set var {*}$args }
}

int a 123
puts a:[set a]
if {[catch { 
  set a xxx
}]} { puts $::errorInfo }

int? b ""
puts b:[set b]
if {[catch { 
  set b 123
  set b yyy
}]} { puts $::errorInfo }