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

What is a decent method to loop through and save part of a string based on a target character?

Hi,

I am working on shortening a string to get a person's name. Essentially, the loop works through each character, expanding with each iteration until a target character is reached. The following is my attempt:

for i=1,1000 do
	local a= string.sub("Emily: My foot hurts.",1,i)
	if i==":" then
		print(a)
		break
	end
end

As you can see, I tried to make the loop as big as possible, depending on how long sentences are because I would add a break to end the loop if the target character is reached (in this case, I want it to stop when there is a colon mark). The 1 should start at the first character of the string, and loop through until it finds the ":". Finally, it would print out the final string, in this case, "Emily".

In theory, this is how the loop would go: E Em Emi Emil Emily [stop] a= "Emily" (intended solution)

I appreciate any help in this matter.

Best,

Houlardy

2 comments

1

I'll answer this tomorrow if nobody gets to it. Don't have time to whip up an entire solution. You'll be using string.gmatch

0

good suggestion, thanks

1 answer

✓ Accepted answer

You are able to use match to match certain patterns in a string. In this case, you can use the pattern "(.*):" to find the characters up to the colon. While this may seem confusing, it makes sense when you split it up. the . represents any character, and the * in front of it means that it will search for 0 or more of any character (to find all characters before the colon if they exist). The colon afterwards means that you want to search for any character up to a colon, and the brackets around the .* tells it what section to return (all characters before the colon, not including the colon).

local str = "Emily: My foot hurts." --poor emily
local upToColon = string.match(str,"(.*):")
for i = 1,#upToColon do
	print(string.sub(upToColon,1,i))
end

3 comments

0

Thanks! I believe I placed the colon before instead of after to save the string regarding what the player said?

0

Answer was very thorough.

1

Yep, colon before should work.

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