Version 0 of C-like syntax for numbers

Updated 2007-02-05 02:35:44

slebetman: This implements what I'd call C-like syntax for numbers in Tcl. Basically, this means that not only can you use infix assignment like x = $y * 2 but you also need to declare the variables before using them. There are other implementations of this available somewhere in this wiki, mostly by Richard Suchenwirth. Prompted by GWM I thought I'd dig up my very simple implementation which have been floating around usenet (google "syntax expressiveness"). Anyway, here's the code:

    proc cleanupVar {name1 name2 op} {
        if {![uplevel 1 [list info exists $name1]]} {
            rename $name1 {}
        }
    }

    proc var {name {= =} args} {
        upvar 1 $name x
        if {[llength $args]} {
            set x [expr $args]
        } else {
            set x {}
        }
        proc $name args [subst -nocommands {
            upvar 1 $name $name
            if {[llength \$args]} {
                set $name [expr [lrange \$args 1 end]]
            } else {
                return $$name
            }
        }]
        uplevel 1 [list trace add variable $name unset cleanupVar]
    }

The following is an example of how to use var:

    proc test {} {
        var x
        var y = 10

        x = $y*2

        return $x
    }
    puts [test]

Another feature is that the variables actually exists in local scope even though their associated commands exists in global scope. This means that the variables can be used recursively:

    proc recursiveTest {x} {
        var y = $x - 1

        if {$y > 0} {
            recursiveTest $y
        }
        puts $y
    }
    recursiveTest 10

should output the numbers 0 to 9. Another test:

    proc test2 {} {
        var x = 10
        puts "this x belongs to test2 = $x"
    }

    proc test3 {} {
        var x = 100
        test2
        puts "this x belongs to test3 = $x"
    }

    test3

output:

  this x belongs to test2 = 10
  this x belongs to test3 = 100

See also infix, Gadgets, Radical Language Modification and Let unknown know