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

How can I get the string after a comma?

For learning purposes, I am creating a script that will create an Instance based on whatever I say.

For example; if I say, "instance/Part, workspace" it will create a part in workspace.

But I don't know how to get everything after the comma.

I also don't know how to make it required to use a comma after they say the instance.

local player=game.Players.LocalPlayer

function newInstance(name, pos)
	local instance=Instance.new(name, pos) --name=name of the instance|pos=parent of the insatnce
end

player.Chatted:connect(function(msg)
	if string.sub(string.lower(msg),1,9)==string.lower("instance/") then
		local ins=string.sub(msg,10,#msg)
		local pos --This is where I am confused. This is supposed to get everything after the comma in ins
		newInstance(ins)
	end
end)

2 answers

String manipulation
Saviour of the universe

To get everything after the first comma, just match it.

function YourCommasOrYourLife(s)
	return s:match("^[^,]+,(.*)$");
end

How does it work?

  • The ^ makes it start from the start of the string. No good matching it midway.
  • The [^,] matches everything that's not a comma.
  • The + matches one or more occurrences of the preceding set.
  • The , matches a comma. Simple.
  • The ( ) marks a capture, which is the bit the function wants to return. You can have as many of these as you want.
  • The . captures anything, and * captures 0 or more occurrences.
  • The $ makes it go all the way to the end. Pointless in this match because * does it anyway, but hey what is learning without unnecessary additions?

2 comments

0

And how would I include this in the script?

0

Just stick the string you want to get the comma bit from into the function. It's really not that difficult, considering this is now skiddie-level implementation implementation.

[ For example; if I say, "instance/Part, workspace" it will create a part in workspace. ] Have you tried "instance/Part, game.Workspace" ?

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