Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Lua

Idiom #227 Copy a list

Create the new list y containing the same elements as the list x.

Subsequent modifications of y must not affect x (except for the contents referenced by the elements themselves if they contain pointers).

local function deepcopy(input)
 local t=type(input)
 if t~="table" then
  return input
 end
 local copy={}
 for k,v in pairs(input) do
  k=deepcopy(k)
  v=deepcopy(v)
  copy[k]=v
 end
 return copy
end
local y=deepcopy(x)

Deepcopy is necessary, since a list could also contains a list.
This deepcopy will be a infinite loop for a list that contains itself.
List<T> y = x.ToList();

Using LINQ

New implementation...
< >
programming-idioms.org