Skip to content

Commit

Permalink
Merge pull request #375 from evo-lua/table-copy-extensions
Browse files Browse the repository at this point in the history
Add table functions for deep and shallow copying
  • Loading branch information
Duckwhale committed Dec 18, 2023
2 parents d5dd1ba + bc0669d commit ae7dff0
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
24 changes: 24 additions & 0 deletions Runtime/Extensions/tablex.lua
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,27 @@ function table.count(object)

return count
end

function table.copy(source)
local deepCopy = {}

for key, value in pairs(source) do
if type(value) == "table" then
deepCopy[key] = table.copy(value)
else
deepCopy[key] = value
end
end

return deepCopy
end

function table.scopy(source)
local shallowCopy = {}

for key, value in pairs(source) do
shallowCopy[key] = value
end

return shallowCopy
end
40 changes: 40 additions & 0 deletions Tests/BDD/table-library.spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -61,4 +61,44 @@ describe("table", function()
assertEquals(table.count({ hi = 42, nil, 43, nil, meep = 44 }), 3)
end)
end)

describe("copy", function()
it("should create a deep copy if the given table contains another table", function()
local tableWithNestedSubtables = {
subtable = { 42 },
12345,
}
local deepCopy = table.copy(tableWithNestedSubtables)
local expectedResult = {
subtable = { 42 },
12345,
}

assertEquals(#deepCopy, #expectedResult)
assertEquals(table.count(deepCopy), table.count(expectedResult))
assertEquals(deepCopy[1], expectedResult[1])
assertEquals(deepCopy.subtable[1], expectedResult.subtable[1])
assert(deepCopy.subtable ~= expectedResult.subtable, "Both tables should not be identical")
end)
end)

describe("scopy", function()
it("should create a shallow copy if the given table contains another table", function()
local tableWithNestedSubtables = {
subtable = { 42 },
12345,
}
local shallowCopy = table.scopy(tableWithNestedSubtables)
local expectedResult = {
subtable = tableWithNestedSubtables.subtable,
12345,
}

assertEquals(#shallowCopy, #expectedResult)
assertEquals(table.count(shallowCopy), table.count(expectedResult))
assertEquals(shallowCopy[1], expectedResult[1])
assertEquals(shallowCopy.subtable[1], expectedResult.subtable[1])
assert(shallowCopy.subtable == expectedResult.subtable, "Both tables should be identical")
end)
end)
end)

0 comments on commit ae7dff0

Please sign in to comment.