Version 6 of unless

Updated 2004-12-17 00:08:24

proc unless {condition body} {

        uplevel [list if "!($condition)" $body]
    }

example:

    unless {$tcl_version >= 8.4} {
        error "package requires Tcl version 8.4 or greater"
    }

Lars H: An alternative implementation, which avoids shimmering:

    proc unless {condition body} {
        uplevel 1 [list if $condition then {} else $body]
    }

glennj: additionally, provide an else clause...

    proc unless {cond body args} {
        set else_body {}
        if {([llength $args] == 2) && ([lindex $args 0] eq "else")} {
            set else_body [lindex $args 1]
        } elseif {[llength $args] > 0} {
            error "usage: [lindex [info level 0] 0] expr body1 ?else body2?"
        }
        uplevel 1 [list if $cond then $else_body else $body]
    }

The above implementations don't work if the command is break or continue; here's a more robust solution:

    proc unless {expr command} {
            global errorInfo errorCode

            set command [list if $expr {} else $command]
            set code [catch {uplevel [list if $expr {} else $command]} result]
            switch -exact -- $code {
                    0   {return $result}
                    1   {return -code error -errorinfo $errorInfo \
                                 -errorcode $errorCode $result}
                    2   {return -code return $result}
                    3   {return -code break}
                    4   {return -code continue}
                    default     {return -code $code $result}
            }
    }

Category Command