在Lua中从表格中减去另一个表格。

我正在尝试在Lua中从一个表中减去另一个表,从而返回表t2减去t1的结果。

这似乎可以工作,但有没有更有效的方法?

function array_sub(t1, t2)

-- 从数组中减去其他数组
-- 用法:nretable = array_sub(T1,T2)--从T2中删除T1

    table.sort(t1)
    for i = 1, #t2 do
        if (t2[i] ~= nil) then
            for j = 1, #t1 do
                if (t2[i] == t1[j]) then
                    table.remove(t2, i)
                end
            end
        end
    end
    return t2
end

local remove = {1,2,3}
local full = {}; for i = 1, 10 do full[i] = i end

local test = {}

local test = array_sub(remove, full)

for i = 1, #test do
    print (test[i])
end
点赞
用户3204551
用户3204551

是的,可以:建立一个包含表t1所有值的查找表,然后从表t2的末尾开始遍历。

function array_sub(t1, t2)
  local t = {}
  for i = 1, #t1 do
    t[t1[i]] = true;
  end
  for i = #t2, 1, -1 do
    if t[t2[i]] then
      table.remove(t2, i);
    end
  end
end

O(#t1)的空间换取了从O(#t1*#t2)加速到O(#t1+#t2)的优势。

2014-04-14 15:21:33
用户748115
用户748115

你可以使用减号对表进行减法运算。

例如:

local t2 = {'a', 'b', 'c', 'd', 'e'}
local t1 = {'b', 'e', 'a'}

t2 = t2 - t1

-- t2 新的值为 {'c', 'd'}
2016-10-03 03:06:21