Multiple distinct objects: Difference between revisions

Content added Content deleted
Line 596: Line 596:


=={{header|Lua}}==
=={{header|Lua}}==
This concept is relevant to tables in Lua
<lang Lua>-- This concept is relevant to tables in Lua
<lang Lua>local table1 = {1,2,3}</lang>
local table1 = {1,2,3}

The following will create a table of references to table1
-- The following will create a table of references to table1
local refTab = {}
<lang Lua>function nRefs (t, n)
local refTab = {}
for i = 1, 10 do refTab[i] = table1 end
for i = 1, 10 do refTab[n] = t end
return refTab
end


-- Instead, tables should be copied using a function like this
local mistake = nRefs(table1, 10)</lang>
function copy (t)
Instead, tables should be copied using a function like this
<lang Lua>function copy (t)
local new = {}
local new = {}
for k, v in pairs(t) do new[k] = v end
for k, v in pairs(t) do new[k] = v end
return new
return new
end</lang>
Now we can create a table of independent copies of table1
<lang Lua>function nCopies (t, n)
local copyTab = {}
for i = 1, 10 do copyTab[i] = copy(table1) end
return copyTab
end
end


-- Now we can create a table of independent copies of table1
local tableOfTables = nCopies(table1, 10)</lang>
local copyTab = {}
for i = 1, 10 do copyTab[i] = copy(table1) end</lang>


=={{header|Mathematica}}==
=={{header|Mathematica}}==