I am somewhat new to string functions. I know generally what both these functions do, but I need someone to explain the difference between them for me. Any replies are appreciated !
1 Like
string.sub() returns a specific part of a string
string.gsub() does the same but it will change to something you wanted
like this
print(string.sub("Hello World!", 1, 4))
-- expected output: "Hello"
print(string.gsub("Hello World!", "Hello", "Hi"))
-- expected output: "Hi World!"
1 Like
string.sub
expects 3 arguments, the string to get a section of, the character index to start and the character index to end at
print(string.sub("Hello!", 1, 3)) --prints Hel
string.gsub
expects a string, the pattern to substitude and what string to replace the substitution
print(string.gsub("Hello there!", "there", "world")) --prints Hello world!
the string documentation gives more info if needed
2 Likes