util.string.len

Shared

Retrieves the length of a string in bytes


Syntax

local length = util.string.len(
    input
)

Parameters

TypeNameDescription
stringinputString to measure

Returns

TypeNameDescription
intlengthLength of the string in bytes

Examples

Get the length of a string
local len = util.string.len("hello")

core.engine.print("info", len) -- 5
Get the length of an empty string
local len = util.string.len("")

core.engine.print("info", len) -- 0
Length includes spaces
local len = util.string.len("hello world")

core.engine.print("info", len) -- 11
Length includes special characters
local len = util.string.len("hello\nworld")

core.engine.print("info", len) -- 11
Length includes null bytes
local len = util.string.len("hello\0world")

core.engine.print("info", len) -- 11
Get the length of a numeric string
local len = util.string.len("12345")

core.engine.print("info", len) -- 5
Use the # operator as an alternative
local len = #"hello"

core.engine.print("info", len) -- 5
Compare util.string.len and # operator
local str = "Lua programming"

core.engine.print("info", util.string.len(str)) -- 15
core.engine.print("info", #str) -- 15
core.engine.print("info", util.string.len(len)) -- 15
Multi-byte UTF-8 characters count as multiple bytes
local str = "hello™"

core.engine.print("info", util.string.len(str)) -- 8
Use length in a conditional check
if util.string.len("test") > 0 then
    core.engine.print("info", "String is not empty")
end
Compare length before and after trimming
local str = "  hello  "
local trimmed = util.string.gsub(str, "^%s+", "")
trimmed = util.string.gsub(trimmed, "%s+$", "")

core.engine.print("info", util.string.len(str)) -- 9
core.engine.print("info", util.string.len(trimmed)) -- 5

On this page