Trying to make my code more clean

I think there is a way to check whether a value from a table (in this case a Enum.Material) is the same as a part’s material in an if statement. This is my current code:

--Table of enums which i am choosing from
local RealisticMaterials = {
	Enum.Material.Wood,
	Enum.Material.WoodPlanks,
	Enum.Material.Fabric,
	Enum.Material.Grass,
	Enum.Material.LeafyGrass
}

--[[
if (in here there will be the logic) then
		FC.Parent = hit
		local scriptclone = script:Clone()
		scriptclone.Parent = hit
end]]--

Is there a way to make the if statement check if the material value of a part is the same as one of the values in the table? Or will I have to use an for loop to run through all the things in the table?

if table.find(material,RealisticMaterials) then
   -- code here
end

There are two methods:
table.find() which will look for the Object based on the index, if found, it will return the index number, otherwise it will be nil, note that this method will not work if you have a Dictionary instead of an Array.

if table.find(RealisticMaterials, BasePart.Material) then -- if index found
    print"Found Material!"
end

the for loop can be used to iterate through all the values within a table no mater if they are Dictionary Keys or Arrays, you are able to set what you want to iterate through with the usages of pairs() and ipairs(), pairs() being used for Dictionaries, while ipairs() is used for Arrays, “i” in ipairs means index.

for _,v in RealisticMaterials do -- iterates through table (pairs and ipairs can be used)
    if BasePart.Material == v then -- if material is equal to the value of the index
        print"Found Material!"
    end
end

There are three items used in this loop, which can be dsecribed as so:

for index, value in Table do

index is the number of the string the key is in.
value is the Item that the Key holdsm which It could be an Instance, number, string, etc.
Table is the table you want to iterate through.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.