6 7 8 9 10 11

Strings

131

In Lua you define a string like that:

name = "Alice"

Quotes

You can use both single quotation marks and double quotation marks to define a string:

tutorial = 'Usually you start a tutorial with "Hello, World!" example'
lesson = "In this lesson we're going to learn Lua syntax"

There is also special syntax for defining a multiline string:

description =
[[Welcome to Lua tutorials!
Now you know how to write "Hello, World!".
Today we will learn how to deal with Lua strings!]]

Operators

To concatenate two strings use .. operator:

print("Hello, " .. "World!")

Using this operator with numbers converts them into a string:

value = 1 .. 2
print(value .. ", " .. type(value))

This will output:

12, string

To get string length use # operator:

name = "Alice"

print(#name)

Simple conversion

There are two simple conversion functions provided: tonumber and tostring:

a = "50"
b = 10
c = "Alice"
d = function () end

print(tonumber(a), type(tonumber(a))); -- 50    number

print(tostring(b), type(tostring(b))); -- 10    string

print(tonumber(c), type(tonumber(c))); -- nil   nil

print(tostring(d), type(tostring(d))); -- function: 0x1e79700   string

Escape sequences

The following escape sequences are available in Lua:

sequences =
{
    "\a", -- Bell
    "\b", -- Back space
    "\f", -- Form feed
    "\n", -- New line
    "\r", -- Carriage return
    "\t", -- Horizontal tab
    "\v", -- Vertical tab
    "\\", -- Backslash
    "\"", -- Double quotes
    "\'", -- Single quotes
    "\[", -- Left square bracket
    "\]"  -- Right square bracket
}
Rate this post:
Lesson 8
Lesson 10
Share this page:

Learning plan

A list of Lua statements which you use to organize control flow of a program
What kind of functions are there and how to write them
How to write tail recursion in Lua properly
9. Strings
How to define and work with strings
10. Arrays
How to deal with arrays or lists
11. Tables
Table is a general Lua data structure, it's all about tables