lua - 合并表与余数 - Lua

标签 lua

我有一个嵌套表(两层)。我想做的是合并(展平?)子表,任何重复项都会溢出到新的键中。 所以输入看起来像

t = {
  [1]  = {
    [1] = "One",
    [3] = "Three"
  },
  [2] = {
    [2] = "Two",
    [3] = "Three"
  },
  [3] = {
    [1] = "One",
    [2] = "Two",
    [4] = "Four"
  }
}

输出看起来像

t = {
  [1] = {
    [1] = "One",
    [2] = "Two",
    [3] = "Three",
    [4] = "Four"
  }  
  [2] = {
    [1] = "One",
    [2] = "Two",
    [3] = "Three"
  }
}

输入表最多有 1000 个键,所以我希望它能够高效地完成。

最佳答案

local bottom, max_btm = {}, 0
for top = #t, 1, -1 do
  for k, v in pairs(t[top]) do
    local btm = bottom[k] or 0
    if btm < top then
      repeat btm = btm + 1
      until btm == top or not t[btm][k]
      if btm ~= top then
        t[btm][k], t[top][k] = v
      end
      bottom[k] = btm
      max_btm = math.max(max_btm, btm)
    end
  end
  if max_btm < top then
    t[top] = nil
  end
end

关于lua - 合并表与余数 - Lua,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35594570/

相关文章:

python - 如何在 Python 中嵌入 Lua?

string - Lua尾随空间删除

function - Lua:使用参数引用表值时出现问题

lua - 在Lua中,a = Account :new{balance = 0} work or is it a typo? 是如何实现的

Lua 文件到数组

regex - 从字符串中删除 '$' 个字符

c++ - Lua、元表和全局变量

c++ - LuaBridge getGlobal 总是返回 nil

function - Lua,设置默认函数参数值。这不会有错吧?

lua - 使用 redis.call ("sinter", ...) 命令将多个集与 lua 脚本相交