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

break a reference

Started by Sewbacca, 05 March 2016 - 10:09 PM
Sewbacca #1
Posted 05 March 2016 - 11:09 PM
How can I copy a table without giving the reference?

For example:

tab = {list = {}}
function setTable(t)
  t = tab
end

My Problem:

s = {}
setTable(s)
print(tab == s) --> true, but I want false

I want do this with a metamethod __index = table.
I don't want to use a function, because I think, that decreasing the performance and I would get the same error.

I hope you can understand me.

Sewbacca
Edited on 05 March 2016 - 10:17 PM
Bomb Bloke #2
Posted 06 March 2016 - 12:06 AM
If you want a different table, then you've got to make a different table.

local tab = {"whatever"}

local function cloneTable(oldTable)
  local newTable = {}

  for key, value in pairs(oldTable) do
    newTable[key] = (type(value) == "table") and cloneTable(value) or value
  end

  return newTable
end

local s = cloneTable(tab)
print(tab == s)  --> false
Edited on 05 March 2016 - 11:13 PM
Sewbacca #3
Posted 06 March 2016 - 10:26 PM
Thanks!

My new Code:

function table.clone(tab)
  local cloneTable = {}

  for key, value in pairs(tab) do
	if type(value) == "table" then
	  cloneTable[key] = table.clone(value)
	else
	  cloneTable[key] = value
	end
  end

  return cloneTable
end
Edited on 07 March 2016 - 08:23 PM