2014-04-14 8 views
5

Sto cercando di sottrarre tabella dalla tabella in Lua, quindi la tabella di ritorno sarà la sottrazione di t1 da t2.sottrarre tabella dalla tabella in Lua

Questo sembra funzionare ma esiste un modo più efficiente di farlo?

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 

risposta

4

Sì, c'è: fare una tabella di ricerca che contiene tutti i valori della tabella T1, e poi passare attraverso tabella T2 a partire dalla fine.

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) spazio per un aumento di velocità O(#t1*#t2)-O(#t1+#t2).

-3

È sufficiente sottrarre la tabella utilizzando il segno meno.

Es.

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

t2 = t2 - t1 

-- t2 new value is {'c', 'd', 'd'} 
+1

Nelle operazioni di arrithmetic native Lua non sono implementate per i valori di tabella standard! Il codice che fornisci causerà un errore ... – Piglet

Problemi correlati