How to clone nested tables?


#1

t <- { x = { y = 0 } };
s <- [];

t.x.y = 1;
s.push(clone(t));
t.x.y = 2;
s.push(clone(t));
t.x.y = 3;
s.push(clone(t));

server.log(s.pop().x.y);
server.log(s.pop().x.y);
server.log(s.pop().x.y);
// Not expected.
3
3
3

// One level deep works fine.
t <- { y = 0 };
s <- [];

t.y = 1;
s.push(clone(t));
t.y = 2;
s.push(clone(t));
t.y = 3;
s.push(clone(t));

server.log(s.pop().y);
server.log(s.pop().y);
server.log(s.pop().y);
// Expected
3
2
1

How to clone “t <- { x = { y = 0 } }” ?


#2

function deepCopy(container){ // container must not have circular references switch(typeof(container)){ case "table": local result = clone container; foreach( k,v in container) result[k] = deepCopy(v); return result; case "array": return container.map(deepCopy); default: return container; } }