Imagine you are designing your own programming language. Very simple language for quite specific purpose. It has functions, loops and variables. And you want to make use of dynamic scoping for variables.
Consider the imaginary example:
var x = "foo"
var count = 0
loop (/* condition */) {
var x = "bar"
// A new stack frame is created for 'x',
// so inside the loop (and any subsequent function calls) it is bound to "bar",
// but outside the loop 'x' is still bound to "foo"
print (x) // output is "bar"
var count = count + 1
}
print (x) // output is "foo"
print (count) // desired output is something above zero, but it's not !!!
My question is - how to make 'count' variable value set inside the loop to be visible outside? How would you do that so it to look more natural (or less confusing) to the users?
- Would you introduce a special keyword to assign a value to an existing variable from the outer scope in additional to the keyword to define a new variable in the current scope? Let's say set and var, or assing and def, etc. But what 'outer scope' would then mean? What if 'count' is not defined right before the loop but instead it is defined earlier somewhere in the invocation stack? Would "set count = ..." assign a value to the variable from that parent of parent of parent frame?
Would you introduce a return value (or tuple) to the loop statement, so that one could write something like:
var count = 0 var count = loop (condition == true) returns [i] { var i = i + 1 }
Wouldn't that look awkward?
- Your solution?
As far as know Perl supports the dynamic scoping using local keyword. How would you implement such example in Perl using dynamic scoped variables only?
Thank you!