What I meant by how do I collect certain characters, what I meant was in a string variable, how do I collect the characters of a specified region in a string as a variable? For example, how do I collect the first two letters of a string, such as the "Ro" of "Roblox is the best online website ever!".
A portion of a string is called a substring. You can get substrings using the string.sub
function:
local text = "abcdefg" local firstTwo = text:sub(1, 2) -- ab local nextTwo = string.sub(text, 3, 5) -- cde -- `text:sub(` and `string.sub(text,` act the same
string.sub
has a few different ways to be used:
text:sub(start, stop)
start
and stop
are both inclusive1
is the first letter, 2
the second, etc-1
is the last letter, -2
the second to last, etctext:sub(start)
text:sub(start, -1)
start
*If the range is empty (entirely before or entirely after the string, or with a stop
before a start
) you get an empty stringstring.sub
never returns nil
and never errors if the parameters are of the right typesExamples:
print( string.sub( "abcdef", 2, 3) ) -- bc print( string.sub("blah", 4) ) -- h print( string.sub("waffle", 2, -2) ) -- affl print( string.sub("cat", 2) ) -- at print( string.sub("cat", 10) ) -- 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?