6

I am trying to subtract table from table in Lua, so the return table will be the subtraction of t1 from t2.

This seems to be working but is there a more efficient way of doing so ?

 function array_sub(t1, t2)

-- Substract Arrays from Array 
-- Usage: nretable =  array_sub(T1, T2)  -- removes T1 from T2

 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
nadigo
  • 107
  • 6

2 Answers2

5

Yes, there is: Make a lookup table containing all values of table t1, and then go through table t2 starting at the end.

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

Traded O(#t1) space for a speedup from O(#t1*#t2) to O(#t1+#t2).

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
-3

You simply subtract the table using minus sign.

Ex.

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

t2 = t2 - t1

-- t2 new value is {'c', 'd', 'd'}
winux
  • 452
  • 4
  • 12
  • 1
    In native Lua arrithmetic operations are not implemented for standard table values! The code you provide will cause an error... – Piglet Oct 03 '16 at 07:25