How to access a variable from a proc in Tcl - tcl

I have a test.tcl file that sources another common.tcl file which contains common procs. Here's a sample content of the common.tcl :
set top_path path.to.top
set path_a $top_path.a
proc x { level } {
if { $level == "top" } {
puts $top_path
}
if { $level == "a" } {
puts $path_a
}
}
proc y {
puts $env(WORKAREA)
}
And here's how the test.tcl looks like :
source $env(PATH_TO_COMMON)/common.tcl
x top
y
The error I'm getting is that the variables (the ones set at the topmost 2 lines of common.tcl) and even the environment variable WORKAREA could not be read (no such variable). No matter if I use set ::env(top_path) and try to read it inside the proc as puts $::env(top_path), I see the same error. Any simple way to resolve this ? There are many lines of setting variables that I need to update.

I don't fully understand your question. How about re-write the script like the following? Add global namespace qualifier :: before the variable names. Also add $ before variable level. And use "eq" instead of "==".
set top_path path.to.top
set path_a $top_path.a
proc x { level } {
if { $level eq "top" } {
puts $::top_path
}
if { $level eq "a" } {
puts $::path_a
}
}
proc y {
puts $::env(WORKAREA)
}

Related

Namespaces and procedures and scope inside namespaces

I'm trying to make a "safe" method of generating request ids for web sockets (just a desktop app not a real server) and want each socket to have its own id generator. All I'm doing is generating ids and recycling them after the request completes, such that the id doesn't grow unlimited throughout a user's session. I used an example concerning closures for a counter in JavaScript from David Flanagan's book and all seems to work well in Tcl but I'd greatly appreciate any advice on how to do this correctly and how I can test that these variables cannot be altered by the main program apart from calling one of the procedures within the namespaces. For example, is it possible to modify the gap list under the WEBS::$sock from the global namespace with [meant without] calling one of the procedures? Thank you.
Also, is there any difference between declaring namespace eval WEBS {} outside proc. ReqIdGenerator and using namespace eval WEBS::$sock inside the procedure? I can see that the results are the same for my little tests but wondered if there was any differences otherwise.
As an aside, in JS using the push and pop methods of arrays, it seems easier to recycle ids on a last-in-first-out basis; but using Tcl lists, it seems easier to use a first-in-first-out basis because using lassign with one variable assigns index 0 to the variable and returns the remaining elements as a new list. The equivalent of array.pop() seems to require more steps. Is that a correct observation? Thank you.
WARNING:
There is an error in this code in that the namespace references $sock and it works only because it is a global variable. If it were not global, the code would throw and error. The best I could find thus far is in this question.
proc ReqIdGenerator {sock} {
namespace eval WEBS {
namespace eval $sock {
variable max 0
variable gap {}
variable open {}
variable sock $sock
proc getId {} {
variable max
variable gap
variable open
if { [llength $gap] > 0 } {
set gap [lassign $gap id]
lappend open $id
return $id
} else {
lappend open [set id [incr max]]
return $id
}
chan puts stdout "Error in getId"
return -1
}
proc delId {id} {
variable max
variable gap
variable open
if { [set i [lsearch $open $id]] == -1 } {
return 1
} elseif { [llength $open] == 1 } {
reset
} else {
lappend gap [lindex $open $i]
set open [lreplace $open $i $i]
}
return 0
}
proc reset {} {
variable max 0
variable gap {}
variable open {}
}
proc getState {{prop "all"}} {
variable max
variable gap
variable open
variable sock
if { $prop eq "all" } {
return [list $max $gap $open]
} elseif { $prop eq "text" } {
return "State of socket $sock: max: $max; gap: $gap; open: $open"
} else {
return [set $prop]
}
}
}
}
}
set sock 123
ReqIdGenerator $sock
set sock 456
ReqIdGenerator $sock
# Add ids 1 through 10 to both sockets
for {set i 0} {$i<10} {incr i} {
WEBS::123::getId
WEBS::${sock}::getId
}
# Delete even ids from socket 456
for {set i 2 } {$i<11} {incr i 2} {
WEBS::${sock}::delId $i
}
# Delete odd ids from socket 123
for {set i 1 } {$i<10} {incr i 2} {
WEBS::123::delId $i
}
chan puts stdout [WEBS::123::getState text]
# => State of socket 123: max: 10; gap: 1 3 5 7 9; open: 2 4 6 8 10
chan puts stdout [WEBS::456::getState text]
# => State of socket 456: max: 10; gap: 2 4 6 8 10; open: 1 3 5 7 9
Lots of questions to unpack here.
how I can test that these variables cannot be altered by the main program apart from calling one of the procedures within the namespaces
You can't. There are no access controls within an interpreter. You can have multiple interpreters and there are strong access controls between them, but that's pretty heavyweight. However, it's conventional to not go rummaging around in a namespace that you don't own to peek at things you've not formally been told about on the grounds that they're liable to be changed at any moment without any sort of notification to you (usually not at runtime, but no guarantees!).
A phrase I've seen used in the community is "If you break it, you get to keep all the pieces".
For example, is it possible to modify the gap list under the WEBS::$sock from the global namespace with calling one of the procedures?
I'm sure it is. Finding it might be tricky, but once you have the name you can change it.
is there any difference between declaring namespace eval WEBS {} outside proc. ReqIdGenerator and using namespace eval WEBS::$sock inside the procedure?
There, assuming you handle the possible differences in name resolution scope of the name of the namespace itself. (That doesn't matter for fully qualified names — names beginning with :: — but relative names might resolve differently.)
The equivalent of array.pop() seems to require more steps. Is that a correct observation?
Yes. 8.7 adds lpop to address this weakness.
Your code appears to be reinventing objects. Use TclOO (or one of the other major object systems such as [incr Tcl] or XOTcl) for that; it's better at the job.
oo::class create ReqIdGenerator {
variable max gap open sock
constructor {sock} {
set max 0
set gap {}
set open {}
set [my varname sock] $sock; # messy because formal parameter
}
method getId {} {
if { [llength $gap] > 0 } {
set gap [lassign $gap id]
lappend open $id
return $id
} else {
lappend open [set id [incr max]]
return $id
}
chan puts stdout "Error in getId"
return -1
}
method delId {id} {
if { [set i [lsearch $open $id]] == -1 } {
return 1
} elseif { [llength $open] == 1 } {
my reset
} else {
lappend gap [lindex $open $i]
set open [lreplace $open $i $i]
}
return 0
}
method reset {} {
set max 0
set gap {}
set open {}
}
method getState {{prop "all"}} {
if { $prop eq "all" } {
return [list $max $gap $open]
} elseif { $prop eq "text" } {
return "State of socket $sock: max: $max; gap: $gap; open: $open"
} else {
return [set [my varname $prop]]
}
}
}
set sock 123
set s1 [ReqIdGenerator new $sock]
set sock 456
set s2 [ReqIdGenerator new $sock]
# Add ids 1 through 10 to both sockets
for {set i 0} {$i<10} {incr i} {
$s1 getId
$s2 getId
}
# Etc.

Tcl increasing a value in a procedure

I just started to learn Tcl. I wanted to write a simple procedure.
When the procedure starts, it opens a browse window to browse for files.
There you can select a file you want to open.
Then a pop-up windows comes up and asks if you want to selected another file.
Every file that you select has to go into an array.
I have to following code:
########## Defining the sub procedures ############
proc open_file {} {
set n 0
set title "Select a file"
set types {
{{GDS files} {.gds} }
{{All Files} * }
}
set filename [tk_getOpenFile -filetypes $types -title $title]
set opendFiles($n) $filename
set n [expr $n + 1]
set answer [tk_messageBox -message "Load another GDS file?" -type yesno -icon question]
if {$answer == yes } {
open_file
} else {
show_files ($opendFiles)
}
}
proc show_files {} {
foreach key [array names opendFiles] {
puts $opendFiles($key)
}
}
########## Main Program ###########
open_file
I having the following problems. Because I always recall the proc 'open_file' the variable $n keeps setting to 0. But I don't know how to recall the opening of the window without recalling the whole subroutine....
The second problem is sending the array to the next proc. When I send to the to the proc 'show_files', I always get the next error : can't read "opendFiles": variable is array.
I can't seem to find both answers..
You need global variables for that. This works for me:
########## Defining the sub procedures ############
set n 0
array set openedFiles {}
proc open_file {} {
set title "Select a file"
set types {
{{GDS files} {.gds} }
{{All Files} * }
}
set filename [tk_getOpenFile -filetypes $types -title $title]
set ::openedFiles($::n) $filename
incr ::n
set answer [tk_messageBox -message "Load another GDS file?" -type yesno -icon question]
if {$answer == yes } {
open_file
} else {
show_files
}
}
proc show_files {} {
foreach key [array names ::openedFiles] {
puts $::openedFiles($key)
}
}
########## Main Program ###########
open_file
Array Problem
In Tcl you can't send arrays to procs. You need to convert them to a list with array get send this list to the proc and than convert it back to an array again with array set.
Global variables are very useful at times, but I believe they are best avoided where possible. In this case I'd rather process the loop and the array in the main program rather than the proc.
Also, where you'd use an array in other programming languages, it's often better to use a list in Tcl, so something like:
proc open_file {} {
set title "Select a file"
set types {
{{GDS files} {.gds} }
{{All Files} * }
}
set filename [tk_getOpenFile -filetypes $types -title $title]
return $filename
}
proc show_files {files} {
foreach file $files {
puts $file
}
}
set openedFiles [list]
set answer yes
while {$answer == yes}
lappend openedFiles [open_file]
set answer [tk_messageBox -message "Load another GDS file?" -type yesno -icon question]
}
show_files $openedFiles
If you're into brevity, show_files could be written
proc show_files {files} {
puts [join $files \n]
}
and, now that it's so short, you could just put it in line, rather than have another proc.
Finally, have you considered what you want to do if the user presses cancel in tk_getOpenFile? In this case filename will be set to an empty (zero-length) string. You could either
ignore these; or
get rid of the tk_messageBox call and have the user press cancel when they have entered as many files as they want.
If you want to just ignore those times when the user pressed cancel, you could do
set filename [open_file]
if {[string length $filename] > 0} {
# The user entered a new filesname - add it to the list
lappend openedFiles $filesname
} else {
# The user pressed cancel - just ignore the filename
}
If you wanted to use cancel to break out of the loop, then the main program becomes something like:
set openedFiles [list]
set filename dummy
while {[string length $filename] > 0} {
set filename [open_file]
if {[string length $filename] > 0} {
lappend openedFiles $filename
}
}
show_files $openedFiles
in this case, you might want to put up a message box right at the start of the main program telling the user what's going on.
For the state of a variable to persist between calls to a procedure, you need to make that variable live outside the procedure. The easiest way is to use a global variable:
# Initialize it...
set n 0
proc open_file {} {
# Import it...
global n
...
# Use it...
set openedFiles($n) $filename
incr n
...
}
Arrays are not values, and as such can't be passed directly to another procedure. You can handle this by passing in the name and using upvar 1 to link a local alias to the variable in the calling stack frame:
proc show_files {varName} {
upvar 1 $varName ary
foreach key [array names ary] {
puts $ary($key)
}
}
Which is called using the name of the array, so no $:
show_files openedFiles
(You could also pass a serialization of the array in with array get openedFiles to serialize and array set ary $serialization to deserialize, but that carries some overhead.)
You probably ought to add that openedFiles variable to the global line, so that it is persistent across all invokations of open_file.

how to declare a variable globally which is used only in proc

i am having a following code:
proc testList {setupFile ""} {
if {$setupFile == ""} {
set setupFile location
}
}
proc run {} {
puts "$setupFile"
}
I am getting syntax error. I know if i declare the setupFile variable outside the proc i.e in the main proc then i can append it with namespace say ::65WL::setupFile to make it global but not getting how to do that if a variable itself is defined in the proc only.
You can refer to the global namespace with ::.
proc testList {{local_setupFile location}} {
# the default value is set in the arguments list.
set ::setupFile $local_setupFile
}
proc run {} {
puts $::setupFile
}
Tcl variables that are not local to a specific procedure run need to be bound to a namespace; the namespace can be the global namespace (there's a special command for that) but doesn't need to be. Thus, to have a variable that is shared between two procedures, you need to give it an exposed name:
proc testList {{setup_file ""}} {
# Use the 'eq' operator; more efficient for string equality
if {$setup_file eq ""} {
set setup_file location
}
global setupFile
set setupFile $setup_file
}
proc run {} {
global setupFile
puts "$setupFile"
}
Now, that's for sharing a full variable. There are some other alternatives provided you only want to share a value. For example, these two possibilities:
proc testList {{setup_file ""}} {
if {$setup_file eq ""} {
set setup_file location
}
# Create a procedure body at run-time
proc run {} [concat [list set setupFile $setup_file] \; {
puts "$setupFile"
}]
}
proc testList {{setup_file ""}} {
if {$setup_file eq ""} {
set setup_file location
}
# Set the value through combined use of aliases and a lambda term
interp alias {} run {} apply {setupFile {
puts "$setupFile"
}} $setup_file
}
There are more options with Tcl 8.6, but that's still in beta.
you can use uplevel, upvar and/or global
proc testList {{setupFile ""}} {
if {$setupFile eq ""} {
set setupFile location;
uplevel set setupFile $setupFile;
}
}
proc run {} {
upvar setupFile setupFile;
puts "$setupFile";
}
or
proc run {} {
global setupFile;
puts "$setupFile";
}
the first is prefered.

Function Overloading in TCL

Are there any packages or any specific way to support function or procedure overloading in TCL??
This is my scenario. I need to write a generic procedure that accepts two or 3 files, wherein I may or may not have the third file (File3)
proc fun { File1 File2 File3 }
{
}
proc fun { File1 File2 }
{
}
There is no overriding in tcl. The second declaration will just replace the first one.
But you handle it with a single procedure. There are two ways at least:
1) Specify the last argument with its default value. Then it will be optional when you calls the function.
proc fun { file1 file2 {file3 ""} } {
if {$file3 != ""} {
# the fun was called with 3rd argument
}
}
2) Use the special argument args, which will contain all arguments as a list. And then analyze the number of arguments actually passed to.
proc fun { args } {
if {[llength $args] == 3} {
# the fun was called with 3rd argument
}
}
Tcl doesn't really support procedure overloading, which makes sense when you consider that it doesn't really have types, per se. Everything is a string that can, depending on value, be interpreted as other types (int, list, etc).
If you can describe what it is you're trying to accomplish (why you think you need overloading), we might be able to make a recommendation about how to accomplish it.
Given the edit to your question, there's a couple different ways to go about it. GrAnd has shown 2 of them. A third, and one I'm a fan of, is to use information specifically about how the command was called:
proc fun { File1 File2 {File3 ""}} { ;# file3 has a default
if {[llength [info level 0]] == 3} { ;# we were called with 2 arguments
;# (proc name is included in [info level 0])
# do what you need to do if called as [fun 1 2]
} else { ;# called with 3 arguments
# do what you need to do if called as [fun 1 2 3]
}
}
Here is an example to hack puts, using a namespace to hide puts and :: to access built-in:
namespace eval newNameSpace {
proc puts {arg} {
set tx "ADDED:: $arg"
::puts $tx
}
puts 102
}
Another way, you can do this:
proc example {
-file1:required
-file1:required
{-file3 ""}
} {
if {$file3 ne ""} {
#Do something ...
}
}
when you call the proc
example -fiel1 info -file2 info2

Tcl global variables in proc declaration

So I have this piece of Tcl code that inherited. Essentially it does the following:
set LOG_ALL 0
set LOG_DEBUG 1
set LOG_INFO 2
set LOG_WARN 3
set LOG_ERROR 4
set LOG_FATAL 5
set LOG_SILENT 6
proc v2 {vimm {log LOG_DEBUG}} {
global LOG_DEBUG
if {$log == $LOG_DEBUG} {
puts "log"
} else {
puts "no log"
}
}
I suspect that the original idea of the designed was to use global variable for the default value of the log parameter. However, it isn't working as expected and I can't find how to write it correctly, assuming it even possible.
Which syntax will be correct?
Thank you for help.
Well, this would be correct:
proc v2 [list vimm [list log $LOG_DEBUG]] {
# ... body same as before
}
But that's just ugly. A neater way is:
proc v2 {vimm {log ""}} { # Any dummy value would do...
global LOG_DEBUG
if {[llength [info level 0]] < 3} {
set log $LOG_DEBUG
}
# ... as before
}
But the true Zen of Tcl is to not use numbers for this task at all, but rather names:
proc v2 {vimm {log "debug"}} {
if {$log eq "debug"} {
puts "log"
} else {
puts "no log"
}
}