Lua - merge tables?

前端 未结 8 1495
忘掉有多难
忘掉有多难 2020-11-28 06:45

I need to merge two tables, with the contents of the second overwriting contents in the first if a given item is in both. I looked but the standard libraries don\'t seem to

8条回答
  •  温柔的废话
    2020-11-28 06:50

    Here's what i came up with based on Doug Currie's answer:

    function tableMerge(t1, t2)
        for k,v in pairs(t2) do
            if type(v) == "table" then
                if type(t1[k] or false) == "table" then
                    tableMerge(t1[k] or {}, t2[k] or {})
                else
                    t1[k] = v
                end
            else
                t1[k] = v
            end
        end
        return t1
    end
    

提交回复
热议问题