Reputation: 1
im trying to compare 2 arrays but i dont know how
for example:
local array1 = { 'friend', 'work', 'privat' }
local array2 = { 'apple', 'juice', 'privat' }
if both arrays have the same value it should do a print.
i know i need to work with something like this
for x in ipairs(array1) do
if x == array2 then
print ("Hi")
end
end
but ofcourse it didnt work. so how can i check if the array1 value contains a values from array2?
Upvotes: 0
Views: 1833
Reputation: 5544
(I'm writing a second answer to account for another possible interpretation of the question.)
If you want to see if array1
contains any value that's also in array2
, you can do the following:
array1
to a set. A set is a new table where the array's values become keys whose values are true
.array2
to see if any of its values are a key in the set.local set = {}
for _, v in ipairs(array1) do
set[v] = true
end
for _, v in ipairs(array2) do
if set[v] then
print'Hi'
-- Use a break statement if you only want to say hi once.
end
end
If the arrays are large, this algorithm should be faster than a nested loop that compares every value in array1
to every value in array2
.
Upvotes: 0
Reputation: 13
how can i check if the array1 value contains a values from array2?
@luther's answer will not always work for your question..
If the arrays are different sizes, it completely fails.
If you have an array where similar element are not in the exact same index, it can return a false negative.
a = {'one', 'two'}; b = {'two', 'one'}
will return false
Using table.sort
to solve this would be a band-aid solution without fixing the real problem.
The function below will work with arrays of different sizes containing elements in any order
function array_compare(a, b)
for ia, va in ipairs(a) do
for ib, vb in ipairs(b) do
if va == vb then
print("matching:",va)
end
end
end
end
In array_compare
we go through all the combinations of elements in table a and table b, compare them, and print if they are equal.
ipairs(table)
uses index, value
(instead of just value
)
For example
local array1 = { 'friend', 'work', 'privat' }
local array2 = { 'apple', 'juice', 'privat' }
array_compare(array1, array2)
will print
matching: privat
Upvotes: 0
Reputation: 5544
Think of it this way: You have to check each element in the first array to its counterpart in the second. If any element is not equal, you know right away that the arrays aren't equal. If every element checks out as equal, the arrays are equal.
local function arrayEqual(a1, a2)
-- Check length, or else the loop isn't valid.
if #a1 ~= #a2 then
return false
end
-- Check each element.
for i, v in ipairs(a1) do
if v ~= a2[i] then
return false
end
end
-- We've checked everything.
return true
end
Upvotes: 3