Skip to content

Commit

Permalink
Fix table.merge for array-based tables.
Browse files Browse the repository at this point in the history
  • Loading branch information
tritao committed Sep 25, 2024
1 parent 5174a98 commit 5884321
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 8 deletions.
20 changes: 12 additions & 8 deletions src/base/table.lua
Original file line number Diff line number Diff line change
Expand Up @@ -373,18 +373,22 @@
local result = {}
local arg = {...}
for _,t in ipairs(arg) do

if type(t) == "table" then
for k,v in pairs(t) do
if type(result[k]) == "table" and type(v) == "table" then
result[k] = table.merge(result[k], v)
else
result[k] = v
if #t > 0 then -- Array-based table
for i = 1, #t do
table.insert(result, t[i])
end
else -- Key-value table
for k, v in pairs(t) do
if type(result[k]) == "table" and type(v) == "table" then
result[k] = table.merge(result[k], v)
else
result[k] = v
end
end
end

else
error("invalid value")
error("invalid value, expected table")
end
end

Expand Down
23 changes: 23 additions & 0 deletions tests/base/test_table.lua
Original file line number Diff line number Diff line change
Expand Up @@ -95,3 +95,26 @@
test.istrue(t[4] == 5)
test.istrue(t[5] == 8)
end

--
-- table.merge() tests
--

function suite.merge()
t = { "a", "b" }
t2 = { "c", "d" }
test.isequal({ "a", "b", "c", "d" }, table.merge(t, t2))

t = { "a", "b" }
t2 = { "c", "d", { "e" } }
test.isequal({ "a", "b", "c", "d", { "e" } }, table.merge(t, t2))

t = { a = 1, b = 2 }
t2 = { c = 3, d = 4 }
test.isequal({ a = 1, b = 2, c = 3, d = 4 }, table.merge(t, t2))

t = { a = 1, b = 2 }
t2 = { c = 3, d = 4, e = { a = 5 } }
print(table.tostring(table.merge(t, t2), 2))
test.isequal({ a = 1, b = 2, c = 3, d = 4, e = { a = 5 } }, table.merge(t, t2))
end

0 comments on commit 5884321

Please sign in to comment.