Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

subtract table from table in Lua

Tags:

lua

lua-table

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
like image 296
nadigo Avatar asked Apr 14 '14 15:04

nadigo


People also ask

How do you create a table in Lua?

The table data structure used in programming to create an array and dictionary. In Lua the table is created by {} as table = {}, which create an empty table or with elements to create non-empty table. After creating a table an element can be add as key-value pair as table1 [key]= “value”.

What are the data structures available in Lua?

Tables are the only data structure available in Lua that helps us create different types like arrays and dictionaries. Lua uses associative arrays and which can be indexed with not only numbers but also with strings except nil. Tables have no fixed size and can grow based on our need.

What is an empty table in Lua programming?

Tables are called objects and they are neither values nor variables. Lua uses a constructor expression {} to create an empty table. It is to be known that there is no fixed relationship between a variable that holds reference of table and the table itself.

What is string format in Lua?

Lua uses tables in all representations including representation of packages. When we access a method string.format, it means, we are accessing the format function available in the string package. Tables are called objects and they are neither values nor variables. Lua uses a constructor expression {} to create an empty table.


1 Answers

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).

like image 127
Deduplicator Avatar answered Sep 17 '22 23:09

Deduplicator