title: Lua copy and split table
body: <p>I have one large table that contains a large number of recursive sub-tables:</p>
  
  <pre><code>table1={p1={def={...}},
          p2={...},
          p3={...},
          ...
          p(n)={...}
  }
  </code></pre>
  
  <p>I need to get a copy of this table that contains only certain sub-tables</p>
  
  <pre><code>plist={"p1", "p3", "p10",...}
  </code></pre>
  
  <p>As a result, I should get a table of the form:</p>
  
  <pre><code>table2={p1={def={...}},
          p3={...},
          p10={...},
          ...
  }
  </code></pre>
  
  <p>table1 should remain unchanged.</p>
  
  <p>I tryed using this code:</p>
  
  <pre><code>function deepcopy(o, seen)
    seen = seen or {}
    if o == nil then return nil end
    if seen[o] then return seen[o] end
    local no
    if type(o) == 'table' then
      no = {}
      seen[o] = no
      for k, v in next, o, nil do
        no[deepcopy(k, seen)] = deepcopy(v, seen)
      end
      setmetatable(no, deepcopy(getmetatable(o), seen))
    else
      no = o
    end
    return o
  end
  
  local table2 = deepcopy(plist, table1)
  </code></pre>
  
  <p>And this:</p>
  
  <pre><code>local function copy(obj, seen)
    if type(obj) ~= 'table' then return obj end
    if seen and seen[obj] then return seen[obj] end
    local s = seen or {}
    local res = setmetatable({}, getmetatable(obj))
    s[obj] = res
    for k, v in pairs(obj) do res[copy(k, s)] = copy(v, s) end
    return res
  end
  local table2 = copy(plist, table1)
  </code></pre>
  
  <p>Both give me not right table2. What code should i use?</p>