Lua - merge tables?

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

    Here's iterative version for deep merge because I don't like potential stack overflows of recursive.

    local merge_task = {}
    function merge_to_left_o(orig, new)
       merge_task[orig] = new
    
       local left = orig
       while left ~= nil do
          local right = merge_task[left]
          for new_key, new_val in pairs(right) do
             local old_val = left[new_key]
             if old_val == nil then
                left[new_key] = new_val
             else
                local old_type = type(old_val)
                local new_type = type(new_val)
                if (old_type == "table" and new_type == "table") then
                   merge_task[old_val] = new_val
                else
                   left[new_key] = new_val
                end
             end
          end
          merge_task[left] = nil
          left = next(merge_task)
       end
    end
    

提交回复
热议问题