Does bc not limit a variable's scope? - scope

Define the function in basic calculator bc as
define void f () { test=42; print "all done\n"; }
I'd have thought the value of test would be limited to the scope of the function f, but no, test equals 42 globally. Is there no way to limit the scope of variables in bc functions? I.e. is there are way to define local variables in bc?

You need to specify an AUTO_LIST in your function definition. From the bc manual,
`define' NAME `(' PARAMETERS `)' `{' NEWLINE
AUTO_LIST STATEMENT_LIST `}'
[...]
The AUTO_LIST is an optional list of variables that are for "local"
use. The syntax of the auto list (if present) is "`auto' NAME, ... ;".
(The semicolon is optional.) Each NAME is the name of an auto
variable. Arrays may be specified by using the same notation as used
in parameters. These variables have their values pushed onto a stack
at the start of the function. The variables are then initialized to
zero and used throughout the execution of the function. At function
exit, these variables are popped so that the original value (at the
time of the function call) of these variables are restored. The
parameters are really auto variables that are initialized to a value
provided in the function call. Auto variables are different than
traditional local variables because if function A calls function B, B
may access function A's auto variables by just using the same name,
unless function B has called them auto variables. Due to the fact that
auto variables and parameters are pushed onto a stack, `bc' supports
recursive functions.
So to keep the test variable "local" in your function, you'd use
define void f () { auto test; test=42; print "all done\n"; }

Related

Is the `def` keyword optional? If so, why use it?

I am aware that a variable can be dynamically typed with the def keyword in Groovy. But I have also noticed that in some circumstances it can be left out, such as when defining method parameters, eg func(p1, p2) instead of func(def p1, def p2). The latter form is discouraged.
I have noticed that this is extendable to all code - anytime you want to define a variable and set its value, eg var = 2 the def keyword can be safely left out. It only appears to be required if not instantiating the variable on creation, ie. def var1 so that it can be instantiated as a NullObject.
Is this the only time def is useful? Can it be safely left out in all other declarations, for example, of classes and methods?
Short answer: you can't. There are some use cases where skipping the type declaration (or def keyword) works, but it is not a general rule. For instance, Groovy scripts allow you to use variables without specific type declaration, e.g.
x = 10
However, it works because groovy.lang.Script class implements getProperty and setProperty methods that get triggered when you access a missing property. In this case, such a variable is promoted to be a global binding, not a local variable. If you try to do the same on any other class that does not implement those methods, you will end up getting groovy.lang.MissingPropertyException.
Skipping types in a method declaration is supported, both in dynamically compiled and statically compiled Groovy. But is it useful? It depends. In most cases, it's much better to declare the type for a better readability and documentation purpose. I would not recommend doing it in the public API - the user of your API will see Object type, while you may expect some specific type. It shows that this may work if your intention is to receive any object, no matter what is its specific type. (E.g. a method like dump(obj) could work like that.)
And last but not least, there is a way to skip type declaration in any context. You can use a final keyword for that.
class Foo {
final id = 1
void bar(final name) {
final greet = "Hello, "
println greet + name + "!"
}
}
This way you can get a code that compiles with dynamic compilation, as well as with static compilation enabled. Of course, using final keyword prevents you from re-assigning the variable, but for the compiler, this is enough information to infer the proper type.
For more information, you can check a similar question that was asked on SO some time ago: Groovy: "def" keyword vs concrete type
in Groovy it plays an important role in Global and Local variable
if the variable name is same with and without def
def is considered local and without def its global
I have explained here in detail https://stackoverflow.com/a/45994227/2986279
So if someone use with and without it will make a difference and can change things.

Node - look up the value of an arbitrary variable

Take this code for an example:
(() => {
const data = []
const ws = new WebSocket('ws:/localhost:5555');
ws.onmessage = (frame) => data.push(frame.data);
})();
Is it possible to look up the value of data without stopping the application, or breakpointing onmessage and waiting for it to occur? Is it possible to just look up the value of any variable that I know to be stored persistently somewhere?
Variables inside a function are private to within that function scope. Only code inside that function scope can examine them.
If you're in the debugger, you will need to be at a breakpoint inside that function scope in order to see that variable.
Sometimes it's appropriate to move the declaration of a variable to a higher scope so that after it is modified inside some local scope, it's value will persist and can be accessed from a higher scope. I don't know what real problem you're trying to solve here to know whether that makes sense for your situation or not.
More likely, since variables like your data variable get modified at some unknown time, the only way some outside code can know when to look at an updated value is by participating in some sort of event system or callback system that notifies outside that it now has a new value. In that case, it's common to just pass the new value to the callback or along with the event. Then the outside code gets the value that way, rather than having to declare it in some parent scope.

local procedures in TCL

I'd like to create a procedure that exists only within a scope of a different proc in TCL.I.e. that just 1 proc can call it. Is it possible? According to this following link, no. :http://wiki.tcl.tk/463But maybe someone knows another way to do it.Thanks.
You can't limit procedures like that, but you can use a lambda term which is almost as good:
proc outside {a b c} {
# Lambda terms are two- or three-element lists.
set inside {{d e f} {
return [expr {$d + $e * $f}]
}}
set total 0
for {set i $a} {$i < $b} {incr i} {
# Lambdas have to be explicitly applied with [apply]
set total [apply $inside $total $c $i]
}
return $total
}
puts [outside 3 7 18]
First element of lambda: list of formal arguments (as for proc)
Second element of lambda: body (as for proc)
Third OPTIONAL element of lambda: context namespace, defaults to the global namespace (::)
The philosophy of Tcl is enabling rather than restricting. The programmer is trusted to do the right thing.
One can use namespaces, same-interpreter aliases, or OO to soft-restrict procedures. They can't be called by mistake, but they can still be accessed by deliberate action. Module procedures are often restricted this way: look at the code in e.g. struct::matrix to see how it can be done.
One can hard-restrict procedures by running the program in a sandbox, an interpreter that withholds a procedure completely or only permits it to be called under special circumstances, such as if called from a certain procedure.
(One can also write a procedure that simply checks who the caller is, but that's easy to spoof.)
Restricting access to a procedure by making its identifier local is a feature of lexical scoping, which Tcl doesn't use. The nearest corresponding mechanism is namespaces.

Is it possible to take the name of a variable and turn it into a string in ActionScript 3.0?

I am making a simple debugger window in ActionScript for myself where I can add and remove variables I want to track. I was to be able to add variables to the list by just doing something like
DebuggerMonitor.trackVar(variable).
My question is, is there any way I can turn "variable" itself (the name, not the value) into a String to be added into a text field?
Depending on how "intelligent" your debugger should be, you could just pass the name along:
DebuggerMonitor.trackVar( variable, "variable" );
since obviously, when used in a context like this, the name should be known at the time you are writing the program.
You can also do some reflection magic to get instance variable names, but it won't work for temp variables (their names are dropped at compilation time):
public function getVariableName( instance:*, match:* ):String {
var typeDescription:XML = describeType( instance );
var variables:XMLList = typeDescription..variable;
var accessors:XMLList = typeDescription..accessor;
for each(var variable:XML in variables)
if(matchesXMLName( instance, variable, match ))
return variable.#name;
for each(var accessor:XML in accessors)
if(matchesXMLName( instance, accessor, match ))
return accessor.#name;
return "No name found.";
}
private function matchesXMLName( instance:*, xml:XML, match:* ):Boolean {
return match == instance[xml.#name.toString()];
}
var varName:String = getVariableName ( myObject, variable );
Using reflections like this will also be quite costly, if used often - you will have to think of a way to cache the type descriptions.
I recommend you check out the as3commons reflections package - there is a lot of useful functionality in there...
Short answer - No :(
You can access the type name but not individual instance names, as these are lost at run-time.
There is a confusion caused by the keyword 'var' because it is used to create several types of bindings.
Lexical bindings (the keyword 'var' was used inside a function).
Dynamic bindings (the keyword 'var' was used to declare a class' field).
Lexical bindings are interpreted by the compiler at compile time as addresses of the registers of the registers space occupied by the function. The names given to lexical bindings perish at this time and it is not possible to restore them at runtime - therefore you can't get the "name" of the variable.
Dynamic bindings are a kind of "public API" of the objects that declare them, they may be accessed from the code that was not compiled together with the code that created them, this is why, for the purpose of reflection the names of these bindings are stored in compiled code. However, ActionScript has no way of referencing LHS values, so you cannot, even if you know the name of the variable and the object declaring it, pass it to another function. But you can look it up in the debugger or by calling describeType on the object declaring the variable. Note that describeType will not show information on private variables even if you are calling it from the scope of the object in question.

passing arguments in different languages

can somebody please explain what is the difference between the following mechanisms of passing arguments: by value, by result, by result-value, with examples if possible, thanks in advance
For general info see Evaluation strategy.
For example code you can check HERE.
Also C# language specification can be useful :
5.1.4 Value parameters
A parameter declared without a ref or
out modifier is a value parameter. A
value parameter comes into existence
upon invocation of the function member
(method, instance constructor,
accessor, or operator) or anonymous
function to which the parameter
belongs, and is initialized with the
value of the argument given in the
invocation. A value parameter normally
ceases to exist upon return of the
function member or anonymous function.
However, if the value parameter is
captured by an anonymous function
(§7.15), its life time extends at
least until the delegate or expression
tree created from that anonymous
function is eligible for garbage
collection. For the purpose of
definite assignment checking, a value
parameter is considered initially
assigned.
5.1.5 Reference parameters
A parameter declared with a ref
modifier is a reference parameter. A
reference parameter does not create a
new storage location. Instead, a
reference parameter represents the
same storage location as the variable
given as the argument in the function
member or anonymous function
invocation. Thus, the value of a
reference parameter is always the same
as the underlying variable. The
following definite assignment rules
apply to reference parameters. Note
the different rules for output
parameters described in §5.1.6.
A variable must be definitely assigned
(§5.3) before it can be passed as a
reference parameter in a function
member or delegate invocation.
Within a function member or anonymous function, a reference
parameter is considered initially
assigned.
Within an instance method or instance
accessor of a struct type, the this
keyword behaves exactly as a reference
parameter of the struct type (§7.6.7).
5.1.6 Output parameters
A parameter declared with an out
modifier is an
output parameter. An output parameter
does not create a new storage
location. Instead, an output parameter
represents the same storage location
as the variable given as the argument
in the function member or delegate
invocation. Thus, the value of an
output parameter is always the same as
the underlying variable. The following definite
assignment rules apply to output
parameters. Note the different rules
for reference parameters described in
§5.1.5.
A variable need not be definitely assigned before it can be passed as
an output parameter in a function
member or delegate invocation.
Following the normal completion of a function member or delegate
invocation, each variable that was
passed as an output parameter is
considered assigned in that execution
path.
Within a function member or anonymous function, an output
parameter is considered initially
unassigned.
Every output parameter of a function member or anonymous
function must be definitely
assigned (§5.3) before the function
member or anonymous function
returns normally.
Within an instance constructor of a
struct type, the this keyword behaves
exactly as an output parameter of the
struct type (§7.6.7).
See C++. The Complete Reference Guide. Herbert Shildt. Third Edition. 139 page.
"Call by value. This method copies the value of an argument into the formal parameter of the subroutine. In this case, changes made to the parameter have no effect on the argument."
"Call by reference is the second way of passing arguments to a subroutine. In this
method, the address of an argument is copied into the parameter. Inside the subroutine,
the address is used to access the actual argument used in the call. This means that
changes made to the parameter affect the argument."
...

Resources