|
From: Twylite <tw...@cr...> - 2008-05-09 11:11:02
|
Hi,
This seems to be one heck of a confusing and verbose discussion ;/
> OK, just to be clear: a variable (Var structure in terms of
> implementation) holds a "strong" reference to a value (Tcl_Obj). That
> variable is then named in one (or more) contexts/namespaces at the
> script level -- i.e., there may exist several "weak" references to
> the variable. Thus there are two levels of reference here: the Var-
> >Tcl_Obj level and the Name (string)->Var level.
>
Usually a "strong reference" is understood to mean a direct reference to
something that exists, while a "weak reference" is an indirect reference
to something that may or may not exist.
For example in C a pointer is a weak reference (the address may be out
of range, or the memory cannot be interpreted as the expected type)
while a reference is a strong reference.
In Java a reference is a strong reference, and you can get weak
references using (strangely enough) WeakReference.
> I need some clarification about what $& notation introduces exactly.
>
I believe Fr?d?ric is suggesting that it is equivalent to an implicit
upvar on the name (in the scope of the called proc), but guarantees that
the variable exists. Using upvar currently provides no such guarantee
because the variable name is a weak reference.
> proc foo v { ... }
> foo $&bar
>
> is roughly equivalent to:
>
> proc foo vName { upvar 1 $vName v; ... }
> foo bar
>
> Is that correct?
>
I believe that is correct if and only if the variable bar exists in the
caller's scope.
Consider:
proc foo {var} { upvar 1 $var myvar ; puts $myvar }
set a 10
foo a -> 10
foo b -> can't read "myvar": no such variable (while executing "puts
$myvar " (procedure "foo" line 1) invoked from within "foo b")
But:
proc foo {var} { puts $var }
set a 10
foo $&a -> 10
foo $&b -> can't read "b": no such variable (while executing "foo $&b")
To added advantage to $& over upvar is that the caller can select to
call by reference _or_ by value (discarding potential output from the proc).
So $& would be kind-of equivalent to the following code, but without the
obvious bugs, and with better error handling:
proc foo {var_or_value} {
if { [uplevel 1 [list info var $var_or_value]] ne {} } {
upvar 1 $var_or_value myvar
} else {
set myvar $var_or_value
}
puts $myvar
}
foo a -> 10 ;# should be foo $&a if using $& syntax, as "foo a" would
pass in "a" as a value
foo alpha -> alpha ;# would be the same if using $& syntax
Fr?d?ric - can you confirm this?
Trevor
|