How to use table.find() for instance's names

I’m using get touching parts to get the parts within an object, but I’m having a hard time scripting when there isn’t a HumanoidRootPart in the table, I assume it’s because the table is with instances, not strings, which is what I’m trying to look for, by name. Anyone got any ideas?

if not table.find(parts, tostring("HumanoidRootPart")) then
		if script.Parent.Health.Value <= script.Parent.Health.Value - script.Parent.PlayerDamage.Value then
			script.Parent.Health.Value += script.Parent.PlayerDamage.Value
		end
	end
1 Like

If you’re trying to search for a part by name, cycle through with a for loop and check for the first object that is a humanoidrootpart;

local hitParts = {} -- // Assume this is the returned value from :GetTouchingParts()
for _, part in ipairs(hitParts) do
    if not part:IsA("BasePart") or part.Name ~= "HumanoidRootPart" then continue end
        -- // your checks here
       break
    end
end

This just finds if a root part was one among those which were returned.

1 Like

The problem with that, is if there are other parts in there, that means there would be loads of signals sent even though even 1 is meant to be sent?

table.find() is the same as a for loop, except it returns the first found index with wanted result.

You can still use table.find() however the result is the same.

local result = table.find(hitParts, HumanoidRootPart::Instance)
-- // Result being the index; this still searches through the whole table, or until it has a result

image

Yes, I assumed you had the HumanoidRootPart defined elsewhere. It’s an example of how to use table.find() to find an Instance that’s indexed. table.find() works like a recursive function:

-- // Essentially table.find()
local function find(Table, Find, Prev)
    local index, value = next(Table, Prev)
    if value == Find then return index end

    return find(Table, Find, index)
end

Given this, you can kind of see how table.find works… you must provide the exact or equal value for the search to return a value; so providing a string for an instance won’t work. It is why I provided a secondary example that you could use.

In short, you cannot use a string to find an instance that’s indexed with table.find().

1 Like
if not part:IsA("BasePart") or part.Name ~= "HumanoidRootPart" then continue end

Be careful with conditional expressions that lack parentheses, they can often lead to unforeseen behavior.

As for the original post, all you need to do is iterate over the return array of part instances.

for _, Part in ipairs(Parts) do --Array of touching parts.
	if Part.Name ~= "HumanoidRootPart" then continue end
	--Part's name is 'HumanoidRootPart'.
end
1 Like