lualua-table

Any way to combine two tables in lua?


Like I got two tables: {["a"] = "aaa"} and {["b"] = "bbb"} And make it into one table: {["a"] = "aaa", ["b"] = "bbb"}

I am already tried this code:

function ListConcat(t1,t2)
    for i=1,#t2 do
        t1[#t1+1] = t2[i]
    end
    return t1
end

local function getkeys(tab)
    local keyset={}
    local n=0
    for k,v in pairs(tab) do
        n=n+1
        keyset[n]=k
    end
    return keyset
end

local function has_value (tab, val)
    for index, value in ipairs(tab) do
        if value == val then
            return true
        end
    end

    return false
end

function TableConcat(t1, t2)
    local key1s = getkeys(t1)
    local key2s = getkeys(t2)
    local keys = ListConcat(key1s, key2s)
    local rtb = {}
    for i=1,#keys do
        local key = keys[i]
        if has_value(key1s, key) then
            rtb[key] = t1[key]
        else
            rtb[key] = t2[key]
        end
    end
    return rtb
end

Where am I wrong, and is there are easier solution? Nothing works, tried other codes. And I don't need to print it like in other people's question.

Dummy code:

local funcs = require("funcs")
a = {["a"] = "a"}
b = {["b"] = "b"}
print(funcs.TableConcat(a, b)) -- Wanted: {["a"] = "a", ["b"] = "b"}
                               -- Returns: {["a"] = "a"}

Solution

  • That's a really overly complicated way to do it.

    In any case, the error lies in ListConcat. This function should return a new list, but you are actually modifying the first list and returning that one. This causes that key1s and keys will be identical. Which makes

        if has_value(key1s, key) then
    

    be true for all keys.

    A much simpler solution is to just do this

    function TableConcat(t1, t2)
        local rtb = {}
        for k,v in pairs(t2) do
            rtb[k] = v
        end
        for k,v in pairs(t1) do
            rtb[k] = v
        end
        return rtb
    end