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?
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 from
th character and ending with the to
th character -- that's inclusive.
Thus the i
th 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. Thus
text:sub(-3, -1)` is the last three characters of the string.