'How to fuse array in Lua
how can I fuse two array into one to be like:
local array1 = {2272, 2271, 2270, 2269}
local array2 = {2267, 2266, 2268, 2265, 2264, 2263, 2262, 2261}
local fusedArray = {2272, 2271, 2270, 2269, 2267, 2266, 2268, 2265, 2264, 2263, 2262, 2261}
or
local array1 = {2292, 2291, 2290, 2289}
local array2 = {2267, 2266, 2268, 2265, 2264, 2263, 2262, 2261}
local fusedArray = {2292, 2291, 2290, 2289, 2267, 2266, 2268, 2265, 2264, 2263, 2262, 2261}
Solution 1:[1]
The standard library can help with this:
local function concatArray(a, b)
local result = {table.unpack(a)}
table.move(b, 1, #b, #result + 1, result)
return result
end
See table.move
and table.unpack
in the docs.
Solution 2:[2]
You'll have to iterate both tables (using ipairs
or pairs
function) and insert elements into a third table. If you can modify one of them, then only iterate the other table and insert its elements into the first one.
Solution 3:[3]
Just copy everything:
local fusedArray = {}
local n=0
for k,v in ipairs(array1) do n=n+1 ; fusedArray[n] = v end
for k,v in ipairs(array2) do n=n+1 ; fusedArray[n] = v end
Solution 4:[4]
Inserting only not presented in original list values:
function isValueInList (value, list)
for i, v in ipairs (list) do if v == value then return true end end
end
function listMergeUnique (listReceiver, listTransmitter)
for i, value in ipairs (listTransmitter) do
if not isValueInList (value, listReceiver) then
table.insert(listReceiver, value)
end
end
end
local a = {1,3,5}
local b = {2,3,4,5,6}
listMergeUnique (a, b) -- listReceiver, listTransmitter
print ('{'..table.concat(a,',')..'}') -- prints {1,3,5,2,4,6}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Paul Kulchenko |
Solution 3 | lhf |
Solution 4 | darkfrei |