string.len()
The string.len()
function in Lua calculates and returns the number of characters in a given string, including spaces and special characters. It is a simple and efficient way to measure string length.
Syntax
string.len(s)
Parameters
- Name
s
- Type
- string
- Description
The string whose length is to be calculated.
Return Value
Returns a number representing the length of the string.
Examples
Example 1: Basic String Length
Determine the length of a simple string.
Example 1
local text = "Hello, Lua!"
local length = string.len(text)
print(length) -- Output: 11
Example 2: Length of an Empty String
The function returns 0
for an empty string.
Example 2
local text = ""
local length = string.len(text)
print(length) -- Output: 0
Example 3: String with Spaces and Special Characters
Spaces and special characters are included in the length calculation.
Example 3
local text = " Lua is fun! "
local length = string.len(text)
print(length) -- Output: 15
Example 4: Comparing Lengths
You can use string.len()
to compare the lengths of different strings.
Example 4
local string1 = "cat"
local string2 = "elephant"
if string.len(string1) < string.len(string2) then
print(string1 .. " is shorter than " .. string2)
end
-- Output: cat is shorter than elephant
Use Cases
- Validation: Ensuring a string meets minimum or maximum length requirements.
- Trimming Logic: Checking if a string exceeds a certain length before truncating.
- Comparison: Determining which of two strings is longer.
See also
string.sub()
: Extracts substrings from a string, often used withstring.len()
to slice strings based on their length.string.rep()
: Repeats a string multiple times, where the length of the result is easily calculated withstring.len()
.