Subscribe Bookmark RSS Feed

Opposite of Default Local

msharp

Super User

Joined:

Jul 28, 2015

So, just some syntactical sugar.

It would be really nice if there was an opposite of declaring local variables for functions.

i.e. instead of:

example= function({a,b}, {c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w},

       c = a+b;

       d = c+a;

       //...

       x = v+w;

       y = x+b;

);

print(x,y);

I could write:

example= function({a,b}, {Default Local, x, y},

       c = a+b;

       d = c+a;

       //...

       x = v+w;

       y = x+b;

);

print(x,y);

5 REPLIES
msharp

Super User

Joined:

Jul 28, 2015

Another example:

x="global scope";

y="global scope";

Names Default to Here(1);

x="here scope";

y="here scope";

print(::x, x, ::y, y);

f = function({}, {Default Local, x},

       x="here scope replaced";

       y="function scope";

       print(x, y);

);

f();

//x != y but it does

print(x, y);

Phil_Brown

Super User

Joined:

Mar 20, 2012

I think if you scope everything, you may get what you want.. Correct me if I'm not following but....For instance

::x="global scope";

::y="global scope";

Names Default to Here(1);

x="here scope";

y="here scope";

print(::x, here:x, ::y, here:y);

f = function({}, {Default Local},

       here:x="here scope replaced";

       ::x = "global scope replaced";

       x = "function scope x";

       y = "function scope y";

       print(here:x, ::x, x,  y);

);

f();

print(x, y); // will be whatever was assigned to these vars in the HERE namespace.

print(::x, ::y); // will be whatever was assigned to these vars in the GLOBAL namespace.


// no way of accessing local vars (actually the point of local).



PDB
Craige_Hales

Staff

Joined:

Mar 21, 2013

I've been using explicit locals in functions.  I think I'll try Default Local in my next project.

Craige
msharp

Super User

Joined:

Jul 28, 2015

I've never used here:x before, but that syntax makes total sense.  Thanks!

vince_faller

Super User

Joined:

Mar 17, 2015

Same goes with local:x if you'd rather explicitly scope on the fly.

f = function({}, {},

       x = "global scope replaced";

       local:x = "function scope x";

       local:y = "function scope y";

       print(::x, local:x,  y);

);

f();

You have to remember to call ::x explicitly because of the scoping rules for unscoped variables.

12892_pastedImage_69.png