Is this code below a good/efficient way to check if two arrays/tables are the same or not. If the tables are the same, it will return true and then remove any functions in the table. If the tables are not the same then it would return and say false.
local _FOLDER = {
Test = 1;
Test2 = 6;
}
local _FOLDER2 = {
Test = 1;
}
local HTTPService = game:GetService("HttpService")
local Same = HTTPService:JSONEncode(_FOLDER)==HTTPService:JSONEncode(_FOLDER2)
local function Reconcile(arr)
for nam,obj in pairs(arr) do
if typeof(obj) == "function" then
arr[nam] = nil
--Remove the function item from the table so that the dataStore can save successfully.
--[NOTE: You cannot save functions.] 4/11/22
elseif typeof(obj) == "table" then
Reconcile(obj)
end
end
end
if Same == true then
Reconcile(_FOLDER)
print(_FOLDER)
else
print(Same)
end
Creative way on how to compare two tables, it’s definitely shorter solution, however the process is little bit inefficient.
The table must be serialized and put into new string object and then compared.
Another solution what you could do is deep-compare of the table and return false on first difference.
Why it’s better is because there’s no need to check other entries if a difference is found.
Obviously the worst case scenario for performance is when the tables are same, since the compare must fully check both tables, but at the end it’s still more efficient than doing serialization and string creation.
it’s simplicity and speed is pretty ok but if you need speed this is the function to use:
function module.isSameTable(tab1 :{}?, tab2 :{}?) :boolean
if type(tab1) ~= "table" or type(tab2)~="table" then return false end
if tab1==tab2 then return true end
for k,v in pairs(tab1) do
if tab2[k] ~= v and not module.isSameTable(v,tab2[k]) then
return false
end
end
for k,v in pairs(tab2) do
if tab1[k] ~= v and not module.isSameTable(v,tab1[k]) then
return false
end
end
return true
end