String
string.sub
Shared
Extracts a substring from a string
Syntax
local result = string.sub(input, start_at, end_at = -1)Parameters
| Type | Name | Description |
|---|---|---|
string | input | String to be extract from |
int | start_at | Character position where extraction begins - negative counts from end |
int | end_at | Character position where extraction ends - negative counts from end |
Returns
| Type | Name | Description |
|---|---|---|
string | result | Extracted substring within string's specified range |
Examples
local result = string.sub("hello world", 1, 5)
engine.print("info", result) --'hello'local result = string.sub("hello world", 7)
engine.print("info", result) --'world'local result = string.sub("hello", -3)
engine.print("info", result) --'llo'local result = string.sub("hello world", 1, -7)
engine.print("info", result) --'hello'local result = string.sub("hello world", 2, -2)
engine.print("info", result) --'ello worl'local char = string.sub("hello", 1, 1)
engine.print("info", char) --'h'local last = string.sub("hello", -1)
engine.print("info", last) --'o'local filename = "document.txt"
local ext = string.sub(filename, -3)
engine.print("info", ext) --'txt'local text = "hello world"
local space = string.find(text, " ")
local firstWord = string.sub(text, 1, space - 1)
engine.print("info", firstWord) --'hello'local str = "[hello]"
local inner = string.sub(str, 2, -2)
engine.print("info", inner) --'hello'local str = "hello"
local copy = string.sub(str, 1, -1)
engine.print("info", copy) --'hello'local result = string.sub("hello", 5, 3)
engine.print("info", result) --''local result = string.sub("hello", 1, 100)
engine.print("info", result) --'hello'local result = string.sub("hello", -5, -1)
engine.print("info", result) --'hello'local date = "2024-01-15"
local year = string.sub(date, 1, 4)
engine.print("info", year) --'2024'local date = "2024-01-15"
local month = string.sub(date, 6, 7)
engine.print("info", month) --'01'local str = "abcdefgh"
for i = 1, #str, 2 do
local chunk = string.sub(str, i, i + 1)
engine.print("info", chunk)
end
--[[
Output:
'ab'
'cd'
'ef'
'gh'
]]local long = "This is a very long string"
local short = string.sub(long, 1, 10).."..."
engine.print("info", short) --'This is a ...'local str = "hello world"
if string.sub(str, 1, 5) == "hello" then
engine.print("info", "Starts with hello")
endlocal str = "prefix_content_suffix"
local content = string.sub(str, 8, 14)
engine.print("info", content) --'content'