This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
byPhins's profile picture

Reference Problem

Started by byPhins, 03 July 2017 - 08:16 PM
byPhins #1
Posted 03 July 2017 - 10:16 PM
Hello,
If i want to copy a table then I need something like this

foo = function(tbl)
local ret = { }
for i, v in pairs(tbl)
  if type(v) == "table" then
   ret[i] = foo(v)
  else
   ret[i] = v
  end
end

return ret
end

newTable = foo(oldTable)
because if I wont use this than

oldtable = { 1, 2, 3}
newtable = oldtable
newtable[2] = 5
-- newtable = {1, 5, 3}
-- oldtable = {1, 5, 3}  <- !!!
now my question is, is there a default function or something else to disable that?
Lupus590 #2
Posted 03 July 2017 - 10:40 PM
There is no function in standard Lua [citation] and I am not aware that CC has provided one.

You could serialise and unserialise the table, but, I belive, that will be slower than calling the function that you created.
Exerro #3
Posted 04 July 2017 - 11:42 PM
You could serialise and unserialise the table, but, I belive, that will be slower than calling the function that you created.
Given that the main two performance issues (imo) would be the table traversal and table creation, the serialising option would only add a load of overhead, and make a few things like functions break it. If performance is no issue, then its simplicity might make it worthwhile though.

The complexity of the copy function entirely depends on the structure of the tables you'll be copying, so it'd help to have some more context.