Is there an easy way to compare to more than one string?

What the title says. I want to compare the name of something to several strings to make sure it doesn’t match before firing, mainly so I don’t have to do

if v.Name ~= name and v.Name ~= name and v.Name ~= name and v.Name ~= name etc…

So, is there a way to shorten this, e.g.

If v.Name ~= name, name, name, name, name

?

If you know the names you’re checking beforehand, you can create a table with the names in them then iterate over that table to compare each value in the table against whatever something’s name is.

local names = {"name1", "name2", "name3", "name4"}
local nameCheck = "name3"
for i, v in pairs(names) do
	if v == nameCheck then
		print(string.format("match! index: %d value: %s", i, v))
	end
end
1 Like

You can also just use a dictionary.

local validNames = {
	name1 = true,
	name2 = true,
	name3 = true
}

if validNames[someName] then
	print(someName.. " is valid")
end

If you want to do something like v.Name ~= name, name, name, you could use a function that goes over a table

local function areStringsDifferent(word, strings)
	for i, v in pairs(strings) do
		if word == v then
			return false
		end
	end
	return true
end

Then later in the script, you could do

if areStringsDifferent("hi", {"hello", "whats up", "abcd"}) then
	print("strings are different")
end

here is a simple solution that you should be able to understand:

local flag  = true --a flag variable to test if it does
local listOfStrings = {"hi","bye","no"}
for _,String in pairs(listOfStrings)do
     if v.Name == String then--checking if the name is equal to any one of the terms
         flag = false--now our flag becomes false
     end
end

if flag then
--only will run if v.Name is different from all the strings
end