Tell if Table is Equal to Another Table

Hello I was wondering how you could tell if a table is equal to another table.

Here is my code:

game.ReplicatedStorage.ReadyUp.OnServerEvent:Connect(function(player)
	table.insert(readyPlayers, player)
	if readyPlayers == game.Players:GetPlayers() then
		print("game start")
	end
end)
1 Like

The answer to this question can be found in another devforum link.

@nooneisback made a script with a function to check if the table is equal

function CheckTableEquality(t1,t2)
    for i,v in next, t1 do if t2[i]~=v then return false end end
    for i,v in next, t2 do if t1[i]~=v then return false end end
    return true
end

You can easily use this function to check between table 1 and table 2.

This should solve your question.

8 Likes

If you wanted to, you could use a metatable based approach instead of using a function to check equality between tables. The metatable you use must have an __eq metamethod which returns a boolean and the two tables must have the same metatable as well.

For example:

local Metatable = {
    __eq = function(Table1, Table2)
        for Index, Value in pairs(Table1) do
            if (Table1[Index] ~= Table2[Index]) then return end
        end

        for Index, Value in pairs(Table2) do
            if (Table2[Index] ~= Table1[Index]) then return end
        end

        return true;
    end
}

--// Inside your ReadyUp
local Players = game:GetService("Players"):GetPlayers();
if (setmetatable(ReadyPlayers, Metatable) == setmetatable(Players, Metatable)) then
    --// Code
end

Personally, I like to use metatables since they allow me to use the usual operators however it’s up to you.

3 Likes

Hello I have a problem. I need to figure out how to see if the tables are the same even if they are sorted differently.

Example:

table1 = {player1, player2}
table2 = {player2, player1}

I have tried to sort the tables so that way they are in the same order, but I do not know how to sort players because you can only sort numbers.

Nevermind I found out how to do it.

How did you do it?
(30char limit)

Don’t mean to bump, but you don’t need to do two loops, instead it should work to just check if the length of the tables are equal, and then if they aren’t do an early return.

function CheckTableEquality(t1,t2)
    if #t1~=#t2 then return false end
    for i,v in next, t1 do if v~=t2[i] then return false end end
    return true
end
1 Like