Array elements being overwritten - please advice

Hello forum,

I have many things achieved since my start with squirrel, but right now I’m stuck at something seemingly trivial. I have following minimal example:
`
user <- {
id = null
count = 0
name = null
}

userarray <- [];

userarray.push(user);

server.log("userarray[0].count: " + userarray[0].count);

user.count = 10;

userarray.push(user);

server.log("userarray[0].count: " + userarray[0].count);
server.log("userarray[1].count: " + userarray[1].count);

`
I want userarray[0].count to stay zero, and userarray[1].count to be 10. I think the problem here is, that in the array actually the pointer to user gets saved. I want to do something like ‘user = new user’ but if I read correct this needs a class of which I create an instance. Here comes the catch: I need so persist that userarray for later and I’ve read somewhere that I can’t persist an array of class instances.

Could somebody please point out what I have to do? I’m really confused right now.

Best regards
Leo

ok, I think I got it sorted out. Here’s what I did:
`
user <- {
id = null
count = 0
name = null
}

userarray <- [];

function pushUser(user){
userarray.push({
id = user.id
count = user.count
name = user.name
});
}

pushUser(user);

server.log("userarray[0].count: " + userarray[0].count);

user.count = 10;

pushUser(user);

server.log("userarray[0].count: " + userarray[0].count);
server.log("userarray[1].count: " + userarray[1].count);

imp.configure(“Serial RX”, [], []);
`

Maybe someone stumbles on this and it helps… if still someone has an advice how to do that in an elegant way, please tell.

Regards
Leo

Your code is probably the most readable way to do it, but this version is shorter:
function pushUser(user){ userarray.push(clone user); }

Peter

Thank you very much - I totally missed that “clone” :slight_smile:

Leo