Nice code! The only problem I see with it, is that if you switched the order of the elements in one of the tables, but still had the same values/strings, it would still indicate a change - which may not be a problem depending on what OP needs. An example:
local table1 = {"a", "s", "l"}
local table2 = {"l", "a", "s"}
local change = CompareTables(table1, table2)
print(change) --> Prints "true" despite the strings being the same ones re-ordered
Here’s a function I took some time to make just now, and it (I think) solves this problem, though it may be quite inneficient. So feel free to change the code however you want of course.
local function compareTables(t1, t2)
local t1Copy = t1
local t2Copy = t2
for i = 1, #t1Copy, 1 do
for j = 1, #t2Copy, 1 do
if t2[j] == t1[i] then
t1Copy[i] = nil
t2Copy[j] = nil
break
end
end
end
if #t1Copy > 0 or #t2Copy > 0 then
return true -- True means there is a change
end
return false -- False means there is no change
end
This will make copies of the two tables - so when I refer to “table” from this point on I’m referring to the copies. It will loop through both tables, and every time it finds a match it’ll remove that specific element from both tables. If both tables have the same elements, it will end off on both tables having 0 elements and returning true
. Otherwise, the tables will end up having more than 0 elements, and thus will return false
, indicating that there was a change.
I hope I helped, and let me know if there’s any thoughts on this code.
EDIT: Sets elements to nil
instead of using table.remove() now. And by the way, this code should work for number or string arrays.