Vital.sandbox
String

string.len

Shared

Retrieves the length of a string in bytes


Syntax

local length = string.len(input)

Parameters

TypeNameDescription
stringinputString to be measured

Returns

TypeNameDescription
intlengthLength of the string in bytes

Examples

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

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

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

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

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

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

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

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

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

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

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

On this page