Let's say I have a textbox, and a user has typed something into the textbox. How would I target, for example, the first 6 letters of the string?
How do I target a certain part of a string?
1 answer
A portion of a string is called a substring. You can get substrings of a string using the string.sub method.
For example, to get the first six characters of "text":
local text = "abc123xyz"
print( text:sub(1, 6) ) -- abc123
:sub(from, to) gives you the piece of the string starting with the fromth character and ending with the toth character -- that's inclusive.
Thus the ith character is text:sub(i, i). So the first character is text:sub(1, 1).
The to is optional. If you don't specify it, then it takes every from from to the end of the string. For example, text:sub(5) in the above would be "23xyz"
It's often helpful to know how long a string is. You can use either #text or text:len().
string.sub let's you use negative numbers for from and to.
-1is the last character in the string,-2is the second to last, etc. Thustext:sub(-3, -1)` is the last three characters of the string.
This discussion is preserved as it was. New answers, comments, and votes are closed.

1 comment
This was really useful. Thanks