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

Help With Finding The Beginning Of A Name?

I have a script that tries to find certain values in the player, the problem is the way the values are named, and it's not something that I can change. I was going to do something like

local p = game.Players.LocalPlayer:GetChildren()
if p.Name = "ClothingSlot"

But the problem is that each ClothingSlot variable has a number at the end of it, so how would I have it check if the name begins with ClothingSlot?

1 answer

✓ Accepted answer

The first and simplest solution IMO is to use the string.sub method to get the first 12 characters of the name.

if string.sub(p.Name,1,12) == "ClothingSlot" then

Or the shorter use of the method:

if p.Name:sub(1,12) == "ClothingSlot" then

And to get the number:

if p.Name:sub(1,12) == "ClothingSlot" then
	local slotNumber = tonumber(p.Name:sub(13)) -- leaving out the second argument will give you a string of the 13'th character to the last

The second solution is to use string.match and string patterns, which can be difficult to learn and understand.

if p.Name:match("^ClothingSlot") then -- returns "ClothingSlot" if the string starts with "ClothingSlot", otherwise returns nil

And using it to check the name and get the number simultaneously:

local slotNumber = p.Name:match("^ClothingSlot(%d+)") -- checks if the string starts with ClothingSlot and returns any digits found after it, otherwise returns nil
if slotNumber then
	slotNumber = tonumber(slotNumber)

I suggest to read up on the wiki about the two methods.

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