Created
July 4, 2015 07:47
-
-
Save qizhihere/cb2a14432d9bf65693ad to your computer and use it in GitHub Desktop.
merge two tables in lua
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function table.merge(t1, t2) | |
for k,v in ipairs(t2) do | |
table.insert(t1, v) | |
end | |
return t1 | |
end |
I write a better one! injoin it!
function table_merge(...)
local tables_to_merge = { ... }
assert(#tables_to_merge > 1, "There should be at least two tables to merge them")
for k, t in ipairs(tables_to_merge) do
assert(type(t) == "table", string.format("Expected a table as function parameter %d", k))
end
local result = tables_to_merge[1]
for i = 2, #tables_to_merge do
local from = tables_to_merge[i]
for k, v in pairs(from) do
if type(k) == "number" then
table.insert(result, v)
elseif type(k) == "string" then
if type(v) == "table" then
result[k] = result[k] or {}
result[k] = table_merge(result[k], v)
else
result[k] = v
end
end
end
end
return result
end
function merge_table(table1, table2)
for _, value in ipairs(table2) do
table1[#table1+1] = value
end
return table1
end
-- example
local table1 = {1, 2, 3}
local table2 = {4, 5, 6}
merged_table = merge_table(table1, table2)
for _, value in ipairs(merged_table) do
print(value)
end
output
------------------
1
2
3
4
5
6
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@LRagji Sorry for such a late reply :-)