2

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}
Doug Currie
  • 40,708
  • 1
  • 95
  • 119
whiteblXK
  • 109
  • 2
  • 3
  • 10
  • Possible duplicate of [Lua - merge tables?](https://stackoverflow.com/questions/1283388/lua-merge-tables) – Josh Apr 18 '18 at 20:13

4 Answers4

5

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.

luther
  • 5,195
  • 1
  • 14
  • 24
1

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.

Paul Kulchenko
  • 25,884
  • 3
  • 38
  • 56
0

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
lhf
  • 70,581
  • 9
  • 108
  • 149
0

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}
darkfrei
  • 122
  • 5