Storing v1
and v2
in a variable makes it more complicated. It is better to construct custom dynamic environments based on Block
, which would be closures, closed over symbolic variables you want.
Here is a generator for such environments:
withBlockedVars = Function[vars, Function[code, Block[vars, code], HoldAll], HoldAll];
Here is how you generate a particular one you need (v1
and v2
here may have global values, this doesn't matter):
myBlock = withBlockedVars[{v1, v2}]
(* Function[code$, Block[{v1, v2}, code$], HoldAll] *)
What you get is a closure, with your specific variables embedded into it. Here is how you can use it:
{v1, v2} = {1, 2};
myBlock[Print[{v1, v2}]]
(* {v1,v2} *)
If you insist on using var
, you can do it like so:
myBlock = Hold[var] /. OwnValues[var] /. Hold[val_]:> withBlockedVars[val],
and then continue in the same way as above.