subtract table from table in Lua
Asked Answered
I

2

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
Illyrian answered 14/4, 2014 at 15:11 Comment(0)
D
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).

Discriminatory answered 14/4, 2014 at 15:21 Comment(0)
H
-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'}
Humpage answered 3/10, 2016 at 3:6 Comment(1)
In native Lua arrithmetic operations are not implemented for standard table values! The code you provide will cause an error...Guyer

© 2022 - 2024 — McMap. All rights reserved.