<instance>.Name == <string> or tostring(<instance>):match(<string>)?

I was wondering if it’s better to use <instance>.Name == <string> or tostring(<instance):match(<string>)? Which one is better for readability and performance wise? or better off :find()?

The first one by far. tostring and match are both unnecessary function calls with overhead.

2 Likes

Definitely == in most cases, the other functions mentioned aren’t used for equality comparisons.

find

will return the position of a substring in a string

if string.find("hello world", "world") then
   print("True, but not equal. (really returns 7)")
end

this evaluates to true if the second argument is anywhere in the first

match

Very similar to find, except it finds a pattern. This is incredibly slow.

if string.match("hello 2 the world", "%d") then
    print("returns 2 because %d will print any number. Returns the found match")
end
2 Likes

It depends. If you’re making a search bar, the second one would be better.

slot.Visible = slot.Name:lower():match(input:lower()) and true or false
1 Like

string.find can also find a pattern.

local _, _, matched = string.find("hello 2 the world", "(%d)")
print(matched)
3 Likes

Correct! I forgot, I usually put the extra true argument to disable matching. I assume this makes it a little faster, I may be wrong.

string.find("hello 2 the world", "%d", 1, true) -- nil

link to the docs (not very verbose)

I’m mainly using it for cases like this

for _,v in workspace:GetChildren() do
    if v.Name == "Hello" then
       print("found")
       break
    end
end

You should use :FindFirstChild() for finding a child by name.

local hello = workspace:FindFirstChild("Hello")
if hello then
    print("found")
end
1 Like

Then that would be better, yes.

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