Title here
Summary here
Lua’s standard library provides many useful string-related functions. Here are some examples to give you a sense of the available operations.
-- We'll use a shorthand for print to keep the examples concise
local p = print
-- Here's a sample of the string functions available in Lua.
-- Note that in Lua, string functions are methods on the string object itself,
-- unlike in some other languages where they might be separate functions.
p("Contains: ", string.find("test", "es") ~= nil)
p("Count: ", select(2, string.gsub("test", "t", "")) + 1)
p("HasPrefix: ", string.sub("test", 1, 2) == "te")
p("HasSuffix: ", string.sub("test", -2) == "st")
p("Index: ", string.find("test", "e"))
p("Join: ", table.concat({"a", "b"}, "-"))
p("Repeat: ", string.rep("a", 5))
p("Replace: ", string.gsub("foo", "o", "0"))
p("Replace: ", (string.gsub("foo", "o", "0", 1)))
p("Split: ", string.gmatch("a-b-c-d-e", "[^-]+"))
p("ToLower: ", string.lower("TEST"))
p("ToUpper: ", string.upper("test"))
When you run this script, you’ll see output similar to:
$ lua string_functions.lua
Contains: true
Count: 2
HasPrefix: true
HasSuffix: true
Index: 2
Join: a-b
Repeat: aaaaa
Replace: f00
Replace: f0o
Split: function: 0x55f8f8c64cb0
ToLower: test
ToUpper: TEST
Note that the Split
function in Lua returns an iterator, not a table, so we print the function itself. To use it, you would typically use it in a for
loop:
for word in string.gmatch("a-b-c-d-e", "[^-]+") do
print(word)
end
This would print each word on a separate line.
Lua’s string manipulation capabilities are quite powerful, and many operations can be performed using pattern matching with string.gsub
and string.gmatch
. For more complex string operations, you might want to look into additional libraries or write custom functions.