Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Metatable, how to subtract two tables?

Asked by 5 years ago
Edited 5 years ago

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

I dont really good speak english so i make a exemple

lua 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

```lua 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?

0
Use __sub. DeceptiveCaster 3761 — 5y

1 answer

Log in to vote
1
Answered by
Rare_tendo 3000 Moderation Voter Community Moderator
5 years ago
Edited 5 years ago

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

```lua 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

Ad

Answer this question