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

liluat.private.clone_table: added support for cloning cyclical tables… #13

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 14 additions & 12 deletions liluat.lua
Original file line number Diff line number Diff line change
Expand Up @@ -63,19 +63,21 @@ end
liluat.private.escape_pattern = escape_pattern

-- recursively copy a table
local function clone_table(table)
local clone = {}

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

return clone
-- adapted from https://gist.github.com/tylerneylon/81333721109155b2d244, copy3() recursive function
local function clone_table(obj, seen)
-- Handle non-tables and previously-seen tables.
if type(obj) ~= 'table' then return obj end
if seen and seen[obj] then return seen[obj] end

-- New table; mark it as seen an copy recursively.
local s = seen or {}
local res = {}
s[obj] = res
setmetatable(res, clone_table(getmetatable(obj), s))
for k, v in pairs(obj) do res[clone_table(k, s)] = clone_table(v, s) end
return res
end

liluat.private.clone_table = clone_table

-- recursively merge two tables, the second one has precedence
Expand Down
25 changes: 25 additions & 0 deletions spec/liluat_spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,31 @@ Hello, <world>!
assert.not_equal(table.a, clone.a)
assert.not_equal(table.a.c, clone.a.c)
end)
it("should clone a self-referencing/cyclical table (with metatable)", function ()
local table = {
a = {
b = 1,
c = {
d = 2
}
},
e = 3
}
table.f = table
table.a.c.g = table.a
setmetatable(table, table)

local clone = liluat.private.clone_table(table)

assert.same(table, clone)
assert.same(getmetatable(table), getmetatable(clone))
assert.not_equal(table, clone)
assert.not_equal(table.a, clone.a)
assert.not_equal(table.a.c, clone.a.c)
assert.not_equal(table.f, clone.f)
assert.not_equal(table.a.c.g, clone.a.c.g)
assert.not_equal(getmetatable(table).a.c.g, getmetatable(clone).a.c.g)
end)
end)

describe("merge_tables", function ()
Expand Down