Tcl/Tk Insight: 函数

风行水上 @ 2009-06-20 08:47:23
标签:
    «目录»

    函数的本质是复用或者说重用。

    函数的存在,使得人们不必每次都从头开始,也促进了分工的发展,从而大大提高了程序设计的整体效率。

    函数的基本属性是调用接口,调用参数和返回值。

    proc

    • Tcl中的函数被称为proc,或者译作“过程”更接近原意
    • 通过return语句返回值
    proc myproc { myparam } {
        puts $myparam
        return 1
    }
    

    参数默认值

    • Tcl允许参数默认值,换句话说,也就是允许缺省参数。
    • 当然为了便于机器识别,参数默认值只能存在于位置靠近末尾的参数。FIXME
    proc myproc {{myparam "default_value"}} {
        puts $myparam
    }
    myproc 123
    myproc
    

    可变长度参数

    • Tcl通过args允许可变长度参数
    proc myproc {arg_1 args} {
        set arg_2 [lindex args 0]
    }
    

    有趣的Tcl Proc

    用"//"来作注释

    proc // {args} { puts $args}
    

    让"#"不再是注释

    proc # {args} {puts $args}
    
    "#" a b c
    \#  d e f
    #  h i j
    

    上现例子中,只有最后一个"#"是真正的注释,之前的两个都会作为命令来执行

    用中文来编程

    proc 循环 {from 到 to body} {
      for "set n $from" "\$n<$to" {incr n} $body
    }
    proc 输出 {args} {puts $args}
    
    循环 1 到 10 {
       输出 $n
    }
    

    上面的例子会循环打印数字1到10。虽然它还不完善,但你看,我们也可以用中文来编程了。

    标签:

      分享到:
      comments powered by Disqus

      28/33ms