Added tableutil.merge.

This commit is contained in:
Robert Zenz 2015-04-06 18:16:34 +02:00
parent f0e1ef97d7
commit 2c3ec0f110
3 changed files with 77 additions and 0 deletions

View File

@ -132,6 +132,11 @@
<td class="summary">Performs a deep/recursive clone on the given table.</td>
</tr>
<tr>
<td class="name" nowrap><a href="#tableutil.merge">tableutil.merge</a>&nbsp;(...)</td>
<td class="summary">Merges the given tables into one instance.</td>
</tr>
<tr>
<td class="name" nowrap><a href="#tableutil.swapped_reindex2d">tableutil.swapped_reindex2d</a>&nbsp;(data, new_x, new_y)</td>
<td class="summary">Reindexes the given 2d array/table, swapping the two dimensions.</td>
@ -194,6 +199,35 @@ The clone of the table.
<dt><a name="tableutil.merge"></a><strong>tableutil.merge</strong>&nbsp;(...)</dt>
<dd>
Merges the given tables into one instance. Note that no cloning is performed so fields may refer to the same instances.
<h3>Parameters</h3>
<ul>
<li>
...: The tables to merge.
</li>
</ul>
<h3>Return value:</h3>
The merged table.
</dd>
<dt><a name="tableutil.swapped_reindex2d"></a><strong>tableutil.swapped_reindex2d</strong>&nbsp;(data, new_x, new_y)</dt>
<dd>
Reindexes the given 2d array/table, swapping the two dimensions.

View File

@ -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)

View File

@ -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.