I am trying to use a Conditional Statement on two tables. it checks if there contents are the same, here is a sample of my code:
local Table1 = { } local Table2 = { } if Table1 ~= Table2 then print("The Content of both Tables is different") end
However, the game keeps thinking the two Tables contents are different, is there anyway i can fix this, thanks
local table1 = {"Two", "Strings"} local table2 = {"Two", "Strings"} local match = false for i = 1, #table1 do match = false for ind, v in pairs(table2) do if table1[i] == v then match = true break end end if match == false then print("Does not match") break end end
On the 2 first lines we declare our tables.
Then we make a variable equal to false.
Then we make a loop that will run an equal amount of times as there are values in table1
.
In the beginning of the loop we once again set the value of our variable, match
to false. Then we make a second loop inside of our first one that will run an equal amount of times as there are values in table2
. That loop will check if there is any value in table2
that matches the current value of table1
. If it does, it will set the value of match
to true to announce that there was a match. But if there wasn't any value that matched. Our first loop will break and print that the tables do not contain the same values.
well the thing is doing {} == {}
will always be false.. the ==
operator checks to see if it's (table)operands are the same object, not wheather they have the same content..
so if i did, local a = {x = 10}
and local b = {x = 10}
, then print(a == b)
will always print false
..
however, if i did b = a
then it print(a == b)
will return true
because the statement implies that a
IS b
..
to check whether or not 2 tables have the same content, you'd have to do something like the following.
function isSame(tableA, tableB) for index, value in pairs(tableB) do if(tableA[index] == value) then return true end end return true end
but this might not work if the table passed to pairs
has less items than the other table, and the items that it has match some of the few that the other one has
local table1, table2 = {},{} for i,v in ipairs(table1) do if table2[i] = table1[i] then print(v..' matches in table2') end end
Its pretty basic. If table2 finds something in table1, it prints that value.