Differences between two tables in Lua

I have two tables in lua (In production, a has 18 elements and b has 8):

local a = {1,2,3,4,5,6}
local b = {3,5,7,8,9}

I need to return 'a', omitting any common elements from 'b' - {1,2,4,6}, similar to the ruby ​​ab command (if a and b were arrays).

The best lua logic I've been able to come up with is this:

local function find(a, tbl)
    for _,a_ in ipairs(tbl) do if a_==a then return true end end
end

function difference(a, b)
   local ret = {}
   for _,a_ in ipairs(a) do
   if not find(a_,b) then table.insert(ret, a_) end
end

return ret
end

local a = {1,2,3,4,5,6}
local b = {3,5,7,8,9}

local temp = {}
temp = difference(a,b)

print(temp[1],temp[2],temp[3],temp[4])

I need to quickly compare these tables (min. 10K times per second). Is there a cleaner way to do this?

======

This is part of the server side of the redis script, and I have to protect my Redis CPU. Outside of a clean Lua process, I have two more options:

1.Create two redis temp keys, then run sinter for large (O) of 42

  • 18 sadd (a)
  • 8 sadd (b)
  • 16 sinter (a, b)

2. Change both a and b so that ruby ​​compares the array and sends the result.

  • .
+4
2

( ):

function difference(a, b)
    local ai = {}
    local r = {}
    for k,v in pairs(a) do r[k] = v; ai[v]=true end
    for k,v in pairs(b) do 
        if ai[v]~=nil then   r[k] = nil   end
    end
    return r
end

a, :

function remove(a, b)
    local ai = {}
    for k,v in pairs(a) do ai[v]=true end
    for k,v in pairs(b) do 
        if ai[v]~=nil then   a[k] = nil   end
    return r
end

, , - :

function diff(a, b)
    Item = front of a
    Diff = front of b
    While Item and Diff
       If Item < Diff then 
           Item is next of a
       Else if Item == Diff then 
           remove Item from a
           Item = next of a
           Diff = next of b
       Else         # else Item > Diff
           Diff = next of b

. , . , - (remove).

, , , a b , alg. 100 a b, , 1000.

+1

:

function difference(a, b)
    local aa = {}
    for k,v in pairs(a) do aa[v]=true end
    for k,v in pairs(b) do aa[v]=nil end
    local ret = {}
    local n = 0
    for k,v in pairs(a) do
        if aa[v] then n=n+1 ret[n]=v end
    end
    return ret
end
+7

Source: https://habr.com/ru/post/1547504/


All Articles