Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Metatable, how to subtract two tables?

Hey devs! I want to make a playlist. I want make two tables.

I dont really good speak english so i make a exemple

	local history = {
		sound1 = {'name', 0000000}
	}
	local list = {sound1 = {'name', 0000000},
				sound2 = {'namE', 0000001},
				sound4 = {'nAmE', 0000004}
	}

I make a first table named history to stored the sounds already listened.

I know than I can substrac two tables if a make metatable. But I dont know how to use it correctly. Exemple of my expected result

	setmetatable(history, list)
	
	function ...()
		-- ??
		local playlist = (history - list)
		-- ??
		for i, s in pairs(playlist) do
			...
		end
		...
	end
	--[[
		expected result:
		playlist = {sound2 = {'namE', 0000001},
				sound4 = {'nAmE', 0000004}
		}
	]]
	}

Sorry if is not precise i don't speak english i'm french and it's hard to talk english. Thanks for anwsers

Can I create that with MetaTable?

1 comment

0

Use __sub.

1 answer

✓ Accepted answer

Well, you'd need to use the __sub metamethod. Here's an example I made:

local t1 = {1, 2, 3, 4}
local t2 = {2, 4}

local mt = {}

function mt.__sub(a, b)
  local function find(v)
    for _, value in pairs(b) do
      if v == value then
        return true
      end
    end
    return false
  end

  for i,v in pairs(a) do
    if find(v) then
      table.remove(a, i)
    end
  end

  return a 
end

function mt.__tostring(t)
  return table.concat(t, ',')
end

t1 = setmetatable(t1, mt)
t2 = setmetatable(t2, mt)

print(t1 - t2)

Result: 1, 3 Because we subtracted 2, and 4 from t2, from t1 which had 1-4

This discussion is preserved as it was. New answers, comments, and votes are closed.