Strings
Strings
Strings are an important component of scripting, as they are used to represent sequences of letters, numbers, and symbols.
Declaring a String
The most common method of declaring strings is to put double quotes ("
) around the characters. The following declaration will cause the variable str
to contain the string Hello world!
:
local str = "Hello world!"
Strings can also be declared using single quotes ('
) which is helpful if the string itself contains double quotes:
Finally, strings can be declared within double brackets, a useful technique for storing multi-line strings:
Combining Strings
Strings can be combined through a method called concatenation. The Lua concatenation syntax is two dots (..
) between the strings, for instance:
Converting Strings
You can easily convert a string to a number by using the tonumber()
function. This function takes one argument (the string) and returns it as a number. If the string doesn’t resemble a number, for example "Hello"
, the tonumber()
function will return nil
.
Conversely, numbers can be converted to strings with the tostring()
function as demonstrated here:
Math and Strings
When you perform math using a string value, Lua will automatically try to convert the string into a number, so you don’t need to wrap the string in tonumber()
beforehand. However, if the string cannot be converted to a number, your script will produce an error.
String Escapes
In double-quoted or single-quoted string declarations (but not bracket declarations), you can use a backslash (\
) to embed almost any character. This is another useful way to include quotes inside a string:
When using string escapes, note that certain characters following a backslash have special meanings. For instance, \n
will produce a newline, not the escaped character n
.