AFAIK, if the hash part of a table is used, it does not preserve the order. There is a very simple way to highlight this.
t1 = {
["foo"] = "val1",
["bar"] = "val2",
["baz"] = "val3",
}
for k,v in pairs(t1) do
print(k, v)
end
On my computer, the order is not preserved:
foo val1
baz val3
bar val2
If the order is important, it is required to use an array.
One (convoluted) way to do it would be the following code. Obviously, I am not aware of the given requirements, so this code might not be the most straight-forward.
t1 = {
{ foo = "val1" }, -- Element t1[1]
{ bar = "val2" }, -- Element t1[2]
{ baz = "val3" } -- Element t1[3]
}
t2 = {
{ foo1 = "val4" }, -- Element t2[1]
{ bar1 = "val5" }, -- Element t2[2]
{ baz1 = "val6" } -- Element t2[3]
}
function merge (t1, t2)
local new_table = {}
-- Copy all the items from the first table
for index = 1, #t1 do
new_table[#new_table+1] = t1[index]
end
-- Copy all the items from the second table
for index = 1, #t2 do
new_table[#new_table+1] = t2[index]
end
-- return the new table
return new_table
end
for k,v in pairs(merge(t1,t2)) do
local subtable = v
for k,v in pairs(subtable) do
print(k,v)
end
end
This would print the following:
foo val1
bar val2
baz val3
foo1 val4
bar1 val5
baz1 val6