Help with string.split and string.gsub

So I looked at the wiki but it was hard for me to understand how they worked.


What this do is that it will take a string and it will try to seperate according what word/symbol you want to seperate. For example, I have a string here named `“Hello I am Zeus!”, and let’s say I want to seperate all of the alphabet “e” inside this string. To do this,

local text = "Hello I am Zeus!"
local splittedText = string.split(text, "e") -- this will become ["H", "llo I am Z", "us!"]

To understand string.gsub, we have to understand what does string.sub does.

string.sub means taking a string, and then returning a sub-string of it, or in simple terms, it returns the alphabets that you want to be returned.


Here is an example.

local text = string.sub("Hello I am Zeus!",1,4)
print(text) -- this will print Hell

The reason why it prints that because of the second and third argument. The second argument asks us which positional index of the string(or which alphabet in the string) to start and then the third argument asks us when or which is the last alphabet will our sub-string be. In this case, the first alphabet of the text is H, and then continuing to e, l, and then the last l is the fourth index of the string, meaning that alphabet, which is l, is going to be our substring’s last alphabet, so it returns whatever number or alphabet that are included in this range, in this case which is 1-4.

Now, string.gsub means global substitution. This is like string.sub but more flexibility. Instead of using numbers, you have to specify a string pattern for the function, then specify a replacement string for that specific pattern. For example:

local text = string.gsub("Hello I am Zeus!","Hello","Hey")
print(text) -- prints Hey I am Zeus!

Let’s see the workflow here, so, the first argument is the string, then the second argument is the pattern we need to find, which is “Hello”, then it will search through the string to match the pattern, and it does! Then, it will replace it to whatever string that is specified in the third argument, which is Hey.

And that’s it.