From 2e00c753d832f1830f2a915fd61d65fd55e3c8d3 Mon Sep 17 00:00:00 2001 From: rxi Date: Tue, 5 May 2015 19:21:56 +0100 Subject: [PATCH] Added function `lume.extend()`, updated README and tests --- README.md | 9 +++++++++ lume.lua | 13 +++++++++++++ test/test_lume.lua | 10 ++++++++++ 3 files changed, 32 insertions(+) diff --git a/README.md b/README.md index 97436c7..524508d 100644 --- a/README.md +++ b/README.md @@ -98,6 +98,15 @@ local t = { 1, 2, 3 } lume.clear(t) -- `t` becomes {} ``` +### lume.extend(t, ...) +Copies all the fields from the source tables to the table `t` and returns `t`. +Tables are iterated in order, so the right-most table overrides existing +fields. +``` +local t = { a = 1, b = 2 } +lume.extend(t, { b = 4, c = 6 }) -- `t` becomes { a = 1, b = 4, c = 6 } +``` + ### lume.shuffle(t) Returns a shuffled copy of the array `t`. diff --git a/lume.lua b/lume.lua index cfc4d57..927c1c7 100644 --- a/lume.lua +++ b/lume.lua @@ -183,6 +183,19 @@ function lume.clear(t) end +function lume.extend(t, ...) + for i = 1, select("#", ...) do + local x = select(i, ...) + if x then + for k, v in pairs(x) do + t[k] = v + end + end + end + return t +end + + function lume.shuffle(t) local rtn = {} for i = 1, #t do diff --git a/test/test_lume.lua b/test/test_lume.lua index f59e71f..607d02d 100644 --- a/test/test_lume.lua +++ b/test/test_lume.lua @@ -145,6 +145,16 @@ tests["lume.clear"] = function() testeq( lume.clear(t) == t, true ) end +-- lume.extend +tests["lume.extend"] = function() + local t = { a = 10, b = 20, c = 30 } + testeq( lume.extend(t) == t, true ) + lume.extend(t, { d = 40 }, { e = 50 }) + testeq( t, { a = 10, b = 20, c = 30, d = 40, e = 50 } ) + lume.extend(t, { a = "cat", b = "dog" }, { b = "owl", c = "fox" }) + testeq( t, { a = "cat", b = "owl", c = "fox", d = 40, e = 50 } ) +end + -- lume.shuffle tests["lume.shuffle"] = function() local t = {1, 2, 3, 4, 5}