Ruud H.G. van Tol on Wed, 11 Sep 2024 12:22:41 +0200


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: How can I keep these values local to my function?



On 2024-09-11 03:15, Joe Slater wrote:
I want to be able to specify binary combinations of options the way that, e.g., vecsort() does. I couldn't see a way to do that so I created a function, makeoptions(), that returns a vector in the form ["a=1","b=2",...] and I use eval() on that vector to create those variables within my function. My problem is that eval() creates them with global scope, and I can't see a way to make them local.

/* Takes a string containing a list of option names and a number whose binary digits represents those options. Returns variables set accordingly. */
makeoptions(s="",options=0)=
{
if(s=="",return());
my(v=strsplit(s," "));
return(vector(#v,i,(Str(v[i],"=",bitand(2^(i-1),options)<>0))))
}
/* A function that uses makeoptions() */
f(n)={
my(a=eval(makeoptions("One Two Three",n)));
my(b=eval(makeoptions("Four Five Six",n+1)));
print("a=",One,Two,Three);
print("b=",Four,Five,Six);
}

Here's the output from my function:
(10:31) > f(2)
a=010
b=110
(10:31) > One \\ Should be undefined
%2 = 0
(10:32) > Four \\ Should be undefined
%3 = 1
Is there a way to make these variables local, or another way to achieve what I want: local named variables set at run time without having a routine along the lines of Opt1=bitand(options,1); Opt2=bitand(options,2); ...

Where you say "local", I think you mean "lexical".

Maybe user defined "Member functions" could be used,
to generate that a.Two means 1.

-- Ruud