Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Finding a relationship between two or more Tables? ROBLOX

Hello everyone I am trying to find a relationship between two tables and I am finding it very difficult.

The first table is a set of values which consist of primarily values that will be used for WalkSpeed.

local tab = {10,20,30,40,50}

The second table is a set of values which consist of values primarily for MaxHealth.

local tab2 = {5,10,15,20,25}

Is there a possible way of finding relationships between these two corresponding tables. Such as 10 and/or 20 appearing in both tables. Any help would be very much appreciated, thank you in advance.

2 comments

0

I think you would still need a for loop of each table, unless you’re making your own so to speak, there’s no built in function for comparing tables by contents

0

I think you are referring to set operations which Lua doesn't have. You can always implement them yourself though.

2 answers

local Array1 = {10,20,30,40,50}
local Array2 = {5,10,15,20,25}

local ValuesInCommon = {}

for _,v in pairs(Array1) do
	for i = 1,#Array2 do
		if v == Array2[i] then
			ValuesInCommon[#ValuesInCommon + 1] = v
		end
	end
end

print(unpack(ValuesInCommon))

10 20

Here is why this works:

We start by creating an table to hold all values that are found to be in common. We then move into a for loop that will represent each Array value (v) separately. Because we are indexing each value separately - we can compare them one at a time to Array2, which is what the second for loop does. It will check if an Array1 value, v, is the same as any values from Array2, and if they are move them into the ValuesInCommon table.

4 comments

0

Explain what you're doing. Simply giving code without an explanation is not helpful.

0

Yeah - a relatively poor post on my end, fixing with an explanation now.

0

Why not use a generic for for the second table as well instead of using Array[i]?

0

I mean you could - what is the benefit of doing this over what I have done above? Just cleaner and more linear code?

You'll need to define what you're looking for first, only then can you look for it.

This discussion is preserved as it was. New answers, comments, and votes are closed.