Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How can I get the string after a comma?

Asked by 8 years ago

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

Log in to vote
2
Answered by 8 years ago

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?
0
And how would I include this in the script? SimplyRekt 413 — 8y
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. User#6546 35 — 8y
Ad
Log in to vote
-1
Answered by 8 years ago

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

Answer this question