From 2c3ec0f1100c8add285b46b6fb1aea025b0bf65c Mon Sep 17 00:00:00 2001 From: Robert Zenz Date: Mon, 6 Apr 2015 18:16:34 +0200 Subject: [PATCH] Added tableutil.merge. --- doc/files/utils/tableutil.html | 34 ++++++++++++++++++++++++++++++++++ test/tableutil.lua | 22 ++++++++++++++++++++++ utils/tableutil.lua | 21 +++++++++++++++++++++ 3 files changed, 77 insertions(+) diff --git a/doc/files/utils/tableutil.html b/doc/files/utils/tableutil.html index 06f3799..31e23ea 100644 --- a/doc/files/utils/tableutil.html +++ b/doc/files/utils/tableutil.html @@ -132,6 +132,11 @@ Performs a deep/recursive clone on the given table. + + tableutil.merge (...) + Merges the given tables into one instance. + + tableutil.swapped_reindex2d (data, new_x, new_y) Reindexes the given 2d array/table, swapping the two dimensions. @@ -194,6 +199,35 @@ The clone of the table. +
tableutil.merge (...)
+
+Merges the given tables into one instance. Note that no cloning is performed so fields may refer to the same instances. + + +

Parameters

+ + + + + + + +

Return value:

+The merged table. + + + +
+ + + +
tableutil.swapped_reindex2d (data, new_x, new_y)
Reindexes the given 2d array/table, swapping the two dimensions. diff --git a/test/tableutil.lua b/test/tableutil.lua index 13c412c..62b2874 100644 --- a/test/tableutil.lua +++ b/test/tableutil.lua @@ -74,3 +74,25 @@ test.run("clone_table", function() test.equals("test", clone.table.deep) end) +test.run("merge", function() + local tablea = { + null = nil, + int = 5, + value = "something" + } + + local tableb = { + bool = true, + value = "overriden", + new_value = "new" + } + + local merged = tableutil.merge(tablea, tableb) + + test.equals(merged.null, nil) + test.equals(merged.int, 5) + test.equals(merged.bool, true) + test.equals(merged.value, "overriden") + test.equals(merged.new_value, "new") +end) + diff --git a/utils/tableutil.lua b/utils/tableutil.lua index df01c66..fcfb935 100644 --- a/utils/tableutil.lua +++ b/utils/tableutil.lua @@ -58,6 +58,27 @@ function tableutil.clone(table) return clone end +--- Merges the given tables into one instance. Note that no cloning is performed +-- so fields may refer to the same instances. +-- +-- @param ... The tables to merge. +-- @return The merged table. +function tableutil.merge(...) + if ... == nil then + return nil + end + + local merged = {} + + for index, table in ipairs({...}) do + for key, value in next, table, nil do + merged[key] = value + end + end + + return merged +end + --- Reindexes the given 2d array/table, swapping the two dimensions. -- -- @param data The array/table to reindex.