Bill Allombert on Fri, 13 Sep 2024 11:02:34 +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 Fri, Sep 13, 2024 at 08:56:10AM +1000, Joe Slater wrote:
> That works as far as confining the scope, but I was hoping to have a
> solution which would allow me to define the variables at run time, rather
> than having them hard coded. I'm surprised that there's apparently no way
> to confine the effect of eval() to a local scope. If my variables have to
> be hard coded anyway, I'll probably use something like my([var1, var2,
> var3]=binary((options+8)%8).

The issue is that eval is its own scope!

? eval("local(a=4);print(a)");a
4
%7 = a

Here maybe a solution to your problem:

? myprogram() = { print([foo,bar,baz]); }
? fun(s,z) = eval(Str("local(",s,"=",z,");myprogram()"));
? fun("foo",3)
[3,bar,baz]
? fun("bar",3)
[foo,3,baz]
? fun("baz",3)
[foo,bar,3]

Cheers,
Bill.