String
string.len
Shared
Retrieves the length of a string in bytes
Syntax
local length = string.len(input)Parameters
| Type | Name | Description |
|---|---|---|
string | input | String to be measured |
Returns
| Type | Name | Description |
|---|---|---|
int | length | Length of the string in bytes |
Examples
--Get length of string
local len = string.len("hello")
engine.print(len) --5--Empty string
local len = string.len("")
engine.print(len) --0--String with spaces
local len = string.len("hello world")
engine.print(len) --11--String with special characters
local len = string.len("hello\nworld")
engine.print(len) --11--String with null byte
local len = string.len("hello\0world")
engine.print(len) --11--Numbers as strings
local len = string.len("12345")
engine.print(len) --5--Using # operator (alternative)
local len = #"hello"
engine.print(len) --5--Comparing both methods
local str = "Lua programming"
engine.print(string.len(str)) --15
engine.print(#str) --15
engine.print(string.len(len)) --15--Multi-byte UTF-8 characters count as multiple bytes
local str = "hello™"
engine.print(string.len(str)) --8--Use in conditionals
if string.len("test") > 0 then
engine.print("String is not empty")
end--Get length before and after trimming
local str = " hello "
engine.print(string.len(str)) --9
local trimmed = string.gsub(str, "^%s+", "")
trimmed = string.gsub(trimmed, "%s+$", "")
engine.print(string.len(trimmed)) --5