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

In simple words, what is the difference between string.sub and string.gsub?

Asked by
sngnn 274 Moderation Voter
5 years ago

I'm not sure how to use these two and would like to know the difference. Here's my code so far:

local tpservice = game:GetService("TeleportService")

local function join(player)
    player.Chatted:Connect(function(msg)
        if msg == "/tpnewserver" --[[string.sub or string.gsub usage here]] then
            local x = tpservice:ReserveServer(game.PlaceId)
            tpservice:TeleportToPrivateServer(game.PlaceId,x,player)
            print("yeet")
        end
    end)
end

game.Players.PlayerAdded:Connect(join)

This also seems like it will work. There's no errors so I might need help with that too.

1 answer

Log in to vote
0
Answered by
Farsalis 369 Moderation Voter
5 years ago
Edited 5 years ago

Hello Qub, first of all, im bad with simple xD. Anyways, here are some examples:

--string.sub--
local str = "Hello, I'm a string."" --Hm. I want to try and grab "Hello", to do this I need to see the starting index of hello (1), and the ending index of hello (5). Now, you may be counting the index, and see that index "5" is "," not "l". Well, like most programming languages, when we need to specify an ending index, meaning the "," is not counted. As the Index ends there.
print(string.sub(str,1,5) --> Output = "Hello"

--string.gsub--
local str = "Hello I'm a string." --Unlike string.sub, string.gsub replaces a certain word or character. As youll see, our str is the 1st argument, what we are looking for is our 2nd argument. and what we are replacing it with is our 3rd argument.
print(string.gsub(str,"Hello","Goodbye") -- There is a 4th argument, which is an Integer, its purpose is if there are multiple Hello's in str, you can set how many Hello's you want to replace. It's default is 1, aka.(The First One It Encounters)

So, in this case string.sub would work. But if you dont always want to specify an exact index, this might be your best option:

local str = "Hello I'm a string."
local si,ei = string.find(str, "Hello") --> Output = 1.5 -- "si" is starting index and "ei" is ending index.
print(string.sub(str,si,ei)) --> Output = "Hello"

Or a simple string.match would do the trick:

local str = "Hello I'm a string."
print(string.match(str, "Hello")) --> Output = "Hello"

Anyways, after those long explanations,

I Hope, some of that stuff helped.

Ad

Answer this question