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!".
✓ ANSWER ACCEPTED
How do I "collect" certain characters in a string?
1 answer
✓ Accepted answer
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)startandstopare both inclusive1is the first letter,2the second, etc-1is the last letter,-2the second to last, etctext: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 astopbefore astart) you get an empty string string.subnever returnsniland never errors if the parameters are of the right types
Examples:
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 xth character on. For example, ("cat"):sub(2) is "at".
This discussion is preserved as it was. New answers, comments, and votes are closed.

2 comments
local nextTwo = string.sub(text, 3, 5) -->cde, not def. Line 10 on the second script should have "print" instead of string.sub
Corrected