diff --git a/README.md b/README.md index 2a26b53..06c3ada 100644 --- a/README.md +++ b/README.md @@ -151,12 +151,11 @@ an array and retains its original keys. lume.filter({1, 2, 3, 4}, function(x) return x % 2 == 0 end) -- Returns {2, 4} ``` -### lume.merge(t, t2 [, retainkeys]) -Merges all the values from the table `t2` into `t` in place. If `retainkeys` is -true the table is not treated as an array and retains its original keys; if `t` -and `t2` have a conflicting key, the value from `t2` is used. +### lume.merge(...) +Returns a new table with all the given tables merged together. If a key exists +in multiple tables the right-most table's value is used. ```lua -lume.merge({2, 3}, {4, 5}) -- Returns {2, 3, 4, 5} +lume.merge({a=1, b=2, c=3}, {c=8, d=9}) -- Returns {a=1, b=2, c=8, d=9} ``` ### lume.concat(...) diff --git a/lume.lua b/lume.lua index 7a0877a..14b478c 100644 --- a/lume.lua +++ b/lume.lua @@ -252,11 +252,16 @@ function lume.filter(t, fn, retainkeys) end -function lume.merge(t, t2, retainkeys) - for k, v in pairs(t2) do - t[retainkeys and k or (#t + 1)] = v +function lume.merge(...) + local rtn = {} + for i = 1, select("#", ...) do + local t = select(i, ...) + local iter = getiter(t) + for k, v in iter(t) do + rtn[k] = v + end end - return t + return rtn end @@ -357,9 +362,9 @@ end function lume.fn(fn, ...) assert(iscallable(fn), "expected a function as the first argument") - local args = {...} + local args = { ... } return function(...) - local a = lume.merge(lume.clone(args), {...}) + local a = lume.concat(args, { ... }) return fn(unpack(a)) end end diff --git a/test/test_lume.lua b/test/test_lume.lua index c44ab0e..ddaf11c 100644 --- a/test/test_lume.lua +++ b/test/test_lume.lua @@ -216,8 +216,9 @@ end -- lume.merge tests["lume.merge"] = function() - testeq( lume.merge({1, 2, 3}, {8, 9, 0}), {1, 2, 3, 8, 9, 0} ) - testeq( lume.merge({a=1, b=2}, {b=3, c=4}, true), {a=1, b=3, c=4} ) + testeq( lume.merge(), {} ) + testeq( lume.merge({x=1, y=2}), {x=1, y=2} ) + testeq( lume.merge({a=1, b=2}, {b=3, c=4}), {a=1, b=3, c=4} ) end -- lume.concat