A string is a sequence of characters that represents text. It is a data type that is commonly used to store and manipulate textual data, such as words, sentences, and paragraphs. In most programming languages, strings are enclosed in quotation marks (either single or double) to distinguish them from other data types.
Basic Syntax
"This an example String" 'Single quoted string' [[ Multiline string Write here and here ]]
You can store the string value into a variable like so:
myName = "Danial"
Or pass the value into function like so:
print("Hello World")
Then, If you run the code above it will display Hello World to the console.
String Manipulation
String manipulation in Lua refers to the process of modifying or transforming strings to achieve a specific result. Lua provides a set of string manipulation functions that can be used to perform various operations on strings, such as searching, replacing, splitting, and joining.
String Concatenation
String concatenation is the process of combining two or more strings into a single string. In Lua, the concatenation operator is represented by two dots “..”. To concatenate two strings, simply use the operator between them. For example:
str1 = "Hello" str2 = "world" str3 = str1 .. " " .. str2 -- concatenates str1, a space, and str2 print(str3) -- prints "Hello world"
In the above example, we concatenated two strings str1
and str2
using the concatenation operator ‘..
‘ and stored the result in str3
. We then printed the concatenated string using the print
function.
Substring
You can extract a specific portion of a string by utilizing the string.sub function and providing the index as a parameter.
myVar = "hello world" var2 = string.sub(myVar,1,5) -- get a substring of text from myVar print(var2)
The given Lua code declares a variable myVar
and assigns it the string value “hello world”.
Then, it declares another variable var2
and assigns it the result of calling the string.sub
function. The string.sub
function takes three arguments: the first is the string that we want to extract a substring from, which in this case is myVar
. The second argument is the starting index of the substring we want to extract, which is 1 in this case (i.e., the beginning of the string). The third argument is the ending index of the substring we want to extract, which is 5 in this case. So var2
will be assigned the substring “hello”.
Finally, the print
function is used to output the value of var2
, which in this case will output “hello” to the console.