So this is a small question I’m asking about substrings please help me understand them in the comments thank you!
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.
what about .gsub and what do substings do and what are they useful for?
Incorrect, sub returns the substring within the specified numbers. gsub replaces a string pattern and returns the edited string.
sub returns a substring, it does not replace anything.
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
.
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