Copy/access the pointer of a integer like with a dictionary

hello, sorry for the weird titlename, let me explain it better
i’d like to store the value of a variable, in another variable. so the opposite of ‘deepCopy’, maybe.
as an example:
when i create a dictionary, ~a = [\x, 0];
then i store it in another variable: ~b = ~a;
i can change ~b and ~a will be also changed: ~b[\x] = 2;
however if i store an integer in another value, ~c = a[\x]; then if i change ~c, then ~a stays the same.
i guess that a declaring a dictionary in another variable would correspond to the pointer of that dictionary. however is it possible to declaring such a variable for an integer value? or is it possible to tether an integer-variable in such a way?
thank you very much!!

You can do this with Ref. As the name implies though, you’re passing by reference and not by pointer. There is a RawPointer class but not sure about its use.

Like so:

~a = Dictionary.newFrom([\x, 0]); //it thinks it's an array otherwise
~b = Ref(~a); //syntactic sugar is `~a
~b.value[\x] = 2;
1 Like

Hey, Thanks for the reponse!
However Ref doesnt solve the problem with referencing a integer value within a dictionary. What i meant was this problem in the following code:

~a = Dictionary.newFrom([\x, 0]);
~b = Ref(~a[\x]);
//once i change ~a, I am looking for a way to change the value of ~b as well
~a.value[\x] = 2;
~b // however it still outputs 0 and not 2.

Is there way of archiving the reference in such a way that ~b would change, if the value \x in a changes?
Thank you !

Maybe you could use a function instead?

~a = Dictionary.newFrom([\x, 0]);
~b = {|val| if (val == nil) {~a[\x]} {~a[\x] = val; ~a[\x]}};

It’s not the same as pass by pointer, but it will touch the value stored in the dictionary either way. Then you can set it to whatever you want. If you need it to be guaranteed an integer, you can specify that in the function somewhere with .asInteger but it might be overkill.

Ref will let you “box” values, but you need to access the value in the box using .get and .set, i.e.

var a = (x: `0);
var b = a.x;
a.x == b && { a.x.get == b.get }

Ps. “address of” operators are complicated for systems with automatic memory managers, c.f.

1 Like