^^Just as the name implies, ask questions to better understand!
Two ways:
length = string.len(string)
OR
var = “abcd”
length = #var
I’m curious, do you want to know the amount of letters in the string, or do you want string length?
if you could answer a couple things for me, that would be stellar:
-
how to find amount of letters in a string
-
how to index each letter
for just letters, you can do:
#string.match(stringValue,"%a+")
more specifically,
local allLetters = string.match(stringValue,"%a+")
local amountOfLetters = #allLetters
You can read more on this here
As said before, string.len(YourStringHere).
local str = "My string is right here"
local length = string.len(str)
Using the string.sub.
let’s say you want to get the 3rd character, you do string.sub(str, 3,3).
Or second:
string.sub(str, 2,2)
Here’s an example of iterating through the string:
local str = "My string is right here"
for i, string.len(str), 1 do
local letter = string.sub(str, i, i)
print(letter)
end
that is getting the character length/string length
not the amount of letters
which would be
#string.match(stringValue,"%a+")
credit to @mc3334
If you’ve got just simple text then len() is OK
If you wanted to deal with emojis and other things then look at utf8.graphemes
local text = "hello😀"
local len = 0
for first, last in utf8.graphemes(text) do
local grapheme = text:sub(first, last)
len = len + 1
print(grapheme)
end
print(len) -- will be 6 here
print(text:len()) -- will be 9 here