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)
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.
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.
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