This is the new home of the egghelp.org community forum.
All data has been migrated (including user logins/passwords) to a new phpBB version.


For more information, see this announcement post. Click the X in the top right-corner of this box to dismiss this message.

Make a string survive rehashing...

Help for those learning Tcl or writing their own scripts.
Post Reply
N
Nimos
Halfop
Posts: 80
Joined: Sun Apr 20, 2008 9:58 am

Make a string survive rehashing...

Post by Nimos »

how can I write something into a file, and reload it after rehashing?
n
nml375
Revered One
Posts: 2860
Joined: Fri Aug 04, 2006 2:09 pm

Post by nml375 »

There are a few various techniques to accomplish that. If your intention is to restore the value of a variable, you might be able to use something like this:

Code: Select all

proc savevars {file varlist} {
 set fId [open $file "WRONLY CREAT TRUNC"]
 foreach var $varlist {
  upvar #0 $var tmp
  puts $fId [list set $var $tmp]
 }
 close $fId
}
Then, all you have to do to save is call savevars with the file to store variables in, and the list of variables to save, and load the savefile as a normal script to restore:

Code: Select all

#save var1, var2, and var3 in myvars.save
savevars "./myvars.save" [list var1 var2 var3]

#Restore saved values
if {[file exists "./myvars.save"]} {source ./myvars.save}
NML_375
n
nml375
Revered One
Posts: 2860
Joined: Fri Aug 04, 2006 2:09 pm

Post by nml375 »

You could also save the variables automatically, using something like this.
In this case, you use register_savevar to tell the script which global variables to save.

Code: Select all

bind evnt - "prerehash" save_rehash
bind evnt - "prerestart" save_rehash

proc save_rehash {evnt} {
 if {[info exists ::savevars]} {
  savevars "./botname.savevars" $::savevars
 }
}

proc register_savevar {var} {
 if {!([info exists ::savevars] && [lsearch -exact $::savevars $var])} {
  lappend ::savevars $var
 }
}

The following modifications to savevars is also recommended, in order to handle non-existent variables.

Code: Select all

proc savevars {file varlist} {
 set fId [open $file "WRONLY CREAT TRUNC"]
 foreach var $varlist {
  upvar #0 $var tmp
  if {[info exists tmp]} {
   puts $fId [list set $var $tmp]
  }
 }
 close $fId
}
NML_375
Post Reply