Search code examples
tclbuilt-in

Does the order of Built-in commands of tcl scripts matter?


I'm using tcl language and using built-in commands to run scripts inside the main tcl script. there are some defined parameters in material_qz.tcl which are needed for the get_qzParam.tcl. Even though get_qzParam.tcl is executed before material_qz.tcl, I don't get any error. My question is if the order of executing built-in commands matters?

source get_qzParam.tcl;
source material_qz.tcl;

Solution

  • The order of defining procs or other commands in Tcl doesn't matter, as long as they have been defined before the command is executed. The body of a proc is not parsed until it is called for the first time. So you can even put total nonsense in there, which will not hurt if it is never executed.

    proc documentation {} {
        This proc doesn't contain valid code, but that
        doesn't lead to an error if it is never invoked.
    }
    

    So, if your get_qzParam.tcl file only defines procs that use things from material_qz.tcl, but those procs are not invoked until after material_qz.tcl is loaded, then everything will just work.


    Commands can also be redefined at run time and then that new definition will be used the next time the command is called. This is a very nice feature that can be used to interactively fix bugs in a running program.

    Another use is to set up a command that will do some preparation and then replace itself for future use. For example, this will only open an sqlite database on the first use:

    proc db {args} {
        package require sqlite3
        sqlite3 db database.db
        tailcall db {*}$args
    }
    

    Here, the sqlite3 command overwrites the db proc. So in future invocations, that new command will be used. But that doesn't affect the already running db proc, which can finish what it is doing. An additional twist is that the db proc calls the db command at the end. But that is the new db command.