Page 2 of 2

Re: Overwrite Data

Posted: Tue Oct 14, 2014 3:24 am
by Positive07
Yeah that is exactly what deepCopy does, your simpler shallow copy does the following

Code: Select all

t = {
    a = {
        b = "hello"
    }
}
for k,v in pairs(t) do
    x[k] = t[k]
end
x.a.b = "bye"
print(t.a.b) --"bye"
print(t==x) --"false"
print(t.a == x.a) --"true"
while deep copy

Code: Select all

t = {
    a = {
        b = "hello"
    }
}
x = deepCopy(t)
x.a.b = "bye"
print(t.a.b) --"hello"
print(t == x) --"false"
print (t.a == x.a) --"false"
I think that Robins code breaks when you do this though:

Code: Select all

t = {
    a = t
}
x = deepCopy(t)
Since it can't handle table loops, if you wanted to do this you would first have to detect the loops with parsing... and that is really hard... maybe there is a library to do this

Re: Overwrite Data

Posted: Tue Oct 14, 2014 4:42 am
by khamarr3524
Right well, it should suffice for my usage. The data files for Units are static and formatted by hand. Nothing strange should be going on in there. I will simply use a recursion method. I'll do something like

Code: Select all

function copyTable(t)
  local tbl = {}
  for k, v in pairs(t) do
    if type(v) == "table" then
     tbl[k] = copyTable(v)
    end
    tbl[k] = v
  end
  return tbl
end
I'm assuming this would work just fine?

Re: Overwrite Data

Posted: Tue Oct 14, 2014 5:02 am
by Positive07
Yeah indeed, it is really similar to deep copy

Re: Overwrite Data

Posted: Tue Oct 14, 2014 5:35 am
by ivan
Minor bug:

Code: Select all

    if type(v) == "table" then
     tbl[k] = copyTable(v)
    end
    tbl[k] = v -- overwrites the copied table reference
Should probably be

Code: Select all

    if type(v) == "table" then
     tbl[k] = copyTable(v)
    else
      tbl[k] = v
    end

Re: Overwrite Data

Posted: Tue Oct 14, 2014 10:36 am
by Robin
Positive07 wrote: I think that Robins code breaks when you do this though:

Code: Select all

t = {
    a = t
}
x = deepCopy(t)
Since it can't handle table loops,
Actually, that's exactly the sort of thing my code fixed, compared to some more naive attempts at deep copying. ;)

(Also, that should really be something like t = {}; t.a = t, but yeah.)