Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Enhancement] hs.fnutils.copy doesn't duplicate subtables #2401

Open
asmagill opened this issue Jun 19, 2020 · 0 comments
Open

[Enhancement] hs.fnutils.copy doesn't duplicate subtables #2401

asmagill opened this issue Jun 19, 2020 · 0 comments

Comments

@asmagill
Copy link
Member

asmagill commented Jun 19, 2020

As the subject says... the following adds options to optionally duplicate subtables found in values and/or keys and maintains the structure of multiple table references within the same table:

local tableCopyNoMT
tableCopyNoMT = function(t, incSubTables, incKeySubTables, seen)
    incSubTables    = incSubTables    or false
    incKeySubTables = incKeySubTables or false
    seen            = seen            or {}
    
    if type(t) ~= "table" then return t end -- failsafe check
    if seen[t] then return seen[t] end

    local copy = {}
    seen[t] = copy
    for k,v in pairs(t) do
        local nK, nV = k, v
        if incKeySubTables and type(nK) == "table" then
            nK = tableCopyNoMT(nK, incSubTables, incKeySubTables, seen)
        end
        if incSubTables    and type(nV) == "table" then
            nV = tableCopyNoMT(nV, incSubTables, incKeySubTables, seen)
        end
        copy[nK] = nV
    end
    return copy
end

My only reason for not creating a pull request yet is because I have some questions:

  • this uses recursion (only when either incSubTables or incKeySubTables is true), which means a sufficiently large table could conceivably overflow the stack... do we think this is an issue? I know that in theory any recursive function can be re-written with an appropriate iterator, I just haven't thought it out yet and I'm trying to decide if it's worth the effort...
  • relies on pairs so subject to metamethods and thus may not create a "true" copy... been thinking about a way to convert this to use next and rawget which would avoid metamethods altogether.
  • doesn't replicate metatables on tables (or subtables), if any... would this be worth adding as well?

It should also be noted that functions and userdata as values/keys may in some cases and senses be "duplicatable" as well, but these are so instance specific that I'm not going to worry about them... it's never come up in my requirements yet at any rate, but the issue of sub-tables has (again, for me at least).

edit - fixed misnamed incKeySubTables in discussion points

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant