【问题标题】:GLua - Getting the difference between two tablesGLua - 获取两个表之间的差异
【发布时间】:2019-05-12 18:37:51
【问题描述】:

免责声明:这是 Glua(Garry's Mod 使用的 Lua)

我只需要比较它们之间的表并返回差异,就像我在对它们进行求导一样。

TableOne = {thing = "bob", 89 = 1, 654654 = {"hi"}} --Around 3k items like that
TableTwo = {thing = "bob", 654654 = "hi"} --Same, around 3k
    
function table.GetDifference(t1, t2)

   local diff = {}
    
      for k, dat in pairs(t1) do --Loop through the biggest table
    
         if(!table.HasValue(t2, t1[k])) then --Checking if t2 hasn't the value
    
            table.insert(diff, t1[k]) --Insert the value in the difference table
            print(t1[k]) 
    
         end
    
      end
    
   return diff
    
end
    
if table.Count(t1) != table.Count(t2) then --Check if amount is equal, in my use I don't need to check if they are exact.
    
   PrintTable(table.GetDifference(t1, t2)) --Print the difference.
    
end

我的问题是两个表之间只有一个差异,这会返回超过 200 个项目。我添加的唯一项目是字符串。我尝试了许多其他类似的函数,但由于表的长度,它们通常会导致堆栈溢出错误。

【问题讨论】:

    标签: algorithm sorting lua lua-table garrys-mod


    【解决方案1】:

    你的问题在于这条线

    if(!table.HasValue(t2, t1[k])) then --Checking if t2 hasn't the value
    

    改成这样:

    if(!table.HasValue(t2, k) or t1[k] != t2[k]) then --Checking if t2[k] matches
    

    现在发生的情况是,您正在查看像 thing = "bob" 这样的条目,然后您正在查看 t2 是否有 "bob" 作为键。但事实并非如此。但是t1 也没有,所以这不应该被视为不同。

    【讨论】:

      猜你喜欢
      • 2011-03-28
      • 2020-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-28
      • 2020-03-22
      相关资源
      最近更新 更多