For example:
local levelInfo = "1_1"
is the string I'm using. How would I split the string so I get two variables for the first 1 and the second 1, because there is a '_' in the middle of it?
Not sure this is possible with string.sub
because the 1 may be a two-digit number and I don't think it can detect when there is a certain character.
You can use string.find
to find where the underscore is and then split the string using string.sub
.
string.find
returns at what character position a pattern is found. A pattern can be any string (in your case it would be _). Once the pattern is found, you can use string.sub
to get the substrings using the information from string.find
as your divider.
1 | local levelInfo = "1_1" |
2 |
3 | local divider = string.find(levelInfo, "_" ) --levelInfo is your string and "_" is your divider. The variable "divider" is now the numerical position of the pattern "_" in the string, |
4 | local substring 1 = string.sub(levelInfo, 1 , divider - 1 ) --I'm assuming you know what string.sub does since you mentioned it in your question.. You have to subtract one from "divider" because "divider" would equal the position of "_" and you want everything before that. |
5 | local substring 2 = string.sub(levelInfo, divider + 1 , string.len(levelInfo)) --Use the same thing as the line above, but divider + 1 is the starting position (add 1 because divider is equal to "_") and the ending position is the total number of characters inside the string (received from string.len). |
Here is more information on string.find.
If I helped you out, be sure to accept my answer!