What are escape characters in Lua?
Overview
Escape characters in programming languages are special character formats that don’t represent themselves in a literal string. Instead, they perform special actions.
In Lua, escape sequence characters will change the default meaning of characters when used in strings. They’re usually a combination of a backslash and a character. Below is a list of escape sequences in Lua and a simple explanation of what these do:
\a: This displays an alarm bell symbol.\bor\\: These print a backslash in our string.\f: This is an escape sequence literal that is used to create a form feed. A form feed causes the cursor to move down to the next line without returning to the start of the line.\n: This is a very popular and commonly used sequence that creates new print lines.\r: This is a carriage return escape sequence. It moves the cursor to the beginning of the line without moving to the next line.\t: This creates a horizontal tab space.\v: This creates a vertical tab space.\": This allows us to insert double quotes in our string without special interpretation.\': This allows us to insert single quotes in our string without special interpretation.
Code
In the code snippet below, we’ll use different escape characters.
--this will show distorted on this editor, because it has no image supportprint("This \f is \f form \f feed \f a \f operation \f")print("This is \n a new line \n continued")print("creates a tab \t space horizontally")print("add double quotes \"\" and single quoutes \'\' safely")
Explanation
- Line 3: We carry out a form feed operation.
- Line 4: We print a new line.
- Line 6: We add tabs to our string.
- Line 7: We add double and single quotes to our strings without their being interpreted specially.