Lua - merge tables?

前端 未结 8 1522
忘掉有多难
忘掉有多难 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:52

    I preferred James version for its simplicity and use it in my utils.lua - i did add a check for table type for error handling.

    function merge(a, b)
        if type(a) == 'table' and type(b) == 'table' then
            for k,v in pairs(b) do if type(v)=='table' and type(a[k] or false)=='table' then merge(a[k],v) else a[k]=v end end
        end
        return a
    end
    

    Thanks for this nice function which should be part of the table class so you could call a:merge(b) but doing table.merge = function(a, b) ... did not work for me. Could even be compressed to a one liner for the real nerds :)

提交回复
热议问题