A portion of a string is called a substring. You can get substrings using the string.sub
function:
3 | local firstTwo = text:sub( 1 , 2 ) |
6 | local nextTwo = string.sub(text, 3 , 5 ) |
string.sub
has a few different ways to be used:
text:sub(start, stop)
start
and stop
are both inclusive
1
is the first letter, 2
the second, etc
-1
is the last letter, -2
the second to last, etc
text:sub(start)
- the same thing as
text:sub(start, -1)
- gets all of the string starting at
start
*If the range is empty (entirely before or entirely after the string, or with a stop
before a start
) you get an empty string
string.sub
never returns nil
and never errors if the parameters are of the right types
Examples:
01 | print ( string.sub( "abcdef" , 2 , 3 ) ) |
04 | print ( string.sub( "blah" , 4 ) ) |
07 | print ( string.sub( "waffle" , 2 , - 2 ) ) |
10 | print ( string.sub( "cat" , 2 ) ) |
13 | print ( string.sub( "cat" , 10 ) ) |
16 | print ( string.sub( "cat" , 3 , 2 ) ) |
1
will include the first letter, 2
will include the second letter, etc.
If you give negative numbers to :sub
, they count backwards -- -1
is the last letter, -2
is the second to last letter, etc. Thus ("waffle"):sub(2, -2)
is "affl"
.
If you only give one number to :sub(x)
, then it acts like :sub(x, -1)
-- from the x
th character on. For example, ("cat"):sub(2)
is "at"
.
Locked by User#24403
This question has been locked to preserve its current state and prevent spam and unwanted comments and answers.
Why was this question closed?