How can I get the number of letters in a string? For example, the string "example"
has 7 letters.
Use #
local str = "example"
print(#str) -- 7
3 Likes
Use the #
operator to get the length of a string or a table.
local s = "Hello World!"
print(#s) --> 12
However, if you only want to include letters and not other characters like spaces, you have to write your own function.
You also have the string.len()
function which I prefer to use over the unary length operator (#).
local str = "example"
print(string.len(str)) --7
Or you can do the same thing in a different syntax,
local str = "my example"
print(str:len())
Which I prefer. BTW
should be str
Just so you’re aware, calling the string library’s functions as methods is slower than calling them directly as functions, this is because the string object’s metatables have to be queried.
local String = "Hello world!"
local ClockTime = os.clock()
for _ = 1, 10000 do
print(string.len(String))
end
print(os.clock() - ClockTime) --1.15
local String = "Hello world!"
local ClockTime = os.clock()
for _ = 1, 10000 do
print(String:len())
end
print(os.clock() - ClockTime) --1.2
The former approach is ~4% more efficient than the latter.
2 Likes
Thanks for that info, never knew there was a difference. I always used the metamethod version as it is easier to type lol.
1 Like