1
votes

Is there a way to define an initialization procedure that's automatically called when a Tcl package is loaded?

In this case, I need to parse a configuration file and set a namespace variable.

I originally had the code in the namespace, outside of a proc, but pkg_mkIndex tried to execute the code when it sourced the file and tossed an error "while sourcing". The package file sources just fine from tclsh, and I'm not sure why it wouldn't do so within pkg_mkIndex.

I can comment out the init routine for pkg_mkIndex's sake, if that's the proper way to do this, but I wondered if there's a built-in way to have init procedures executed automatically, a la C's main().

1

1 Answers

1
votes

but I wondered if there's a built-in way to have init procedures executed automatically

It is common practise to provide an initialisation script as part of your package ifneeded script, e.g.:

package ifneeded mypkg 1.0.0 "source [list [file join $dir mypkg.tcl]]; source [list [file join $dir myinit.tcl]]"

Using pkg_mkIndex turns out not particularly helpful in anything non-trivial, as it attempts to (partially) evaluate the source files with all their dependencies. Better handicraft the pkgIndex.tcl script and separate the concerns (pkg definition, pkg initialisation; see above).