Difference between .sub .gsub and :sub and what do they do?

So this is a small question I’m asking about substrings please help me understand them in the comments thank you!

1 Like

For the methods with a period, you have to do string.sub(“string”, 1, 3).

For the methods with a colon, you have to do (“string”):sub(1, 3)

The difference is the with the period, you have to input the string within the function, and with the colon, you do not have to input the string.

7 Likes

what about .gsub and what do substings do and what are they useful for?


https://developer.roblox.com/en-us/api-reference/lua-docs/string

1 Like

Here is the API Reference for the string library which explains all of the functions.

Incorrect, sub returns the substring within the specified numbers. gsub replaces a string pattern and returns the edited string.

1 Like

sub returns a substring, it does not replace anything.

1 Like

So I get the .sub and the :sub but I don’t get .gsub @COUNTYL1MITS said it replaces the string pattern and returns a edited string so does that mean .sub returns a substing? and how would all of these even be useful in code?

These methods are useful for string manipulation.

Here is an example of sub:

local str = “foo bar”
print(str:sub(1, 3)) — foo

So in this script, sub took grabbed the characters from the first character to third. Then it returned the substring, which was foo.

Here is an example of gsub:

local str = “foo bar”
print(str:gsub(“bar”, “x”)) — foo x

So in this script, gsub went and found any instances of bar and replaced them with x. Then it returned the modified string, which was foo x.

6 Likes

When using : , self is passed automatically while using ., self isn’t passed automatically.

string.sub(“string”, 1, 3) --> string is passed as self (first argument)
string:sub(1, 3) --> string is passed as self automatically

3 Likes