I am new comming of tcl. How to use tcl to imitate "set" command?
I try to build like below cold, but below code with error: unknown command name:
proc my_set {varName {value ""}} {
uplevel 0 [set $varName $value]
}
my_set a "123"
my_set b(a) "good"
puts $a; #expected: 123
puts $b(a); #expected: good
In your
my_setproc, the scriptset $varname $valueis called, and then its result is passed as an argument to theuplevelcommand, which will try to run that result as a script.To have it do what you want:
or
or
The first (using
uplevel) constructs the command to run in the caller's frame (the1argument) as a list, and thenuplevelruns that list as a command 1 frame up the stack.The second aliases the local variable
targetin themy_setproc to the variable whose name is in thevarnamevariable,1level up the stack. So setting thetargetvariable within themy_setproc also sets the variable called$varnamein the caller's frame.The third (using
tailcall) replaces the callframe of themy_setwith the commandset, which is then executing as if it was called from the parent frame.Of the three, I would probably pick the second (using
upvar) because there is less potential for nasty surprises waiting in your future (uplevelis essentiallyeval- incautious use can open remote code execution vulnerabilities), and, unless you like obscure constructions for their own sake, thetailcallimplementation is probably just too weird.