This first edition was written for Lua 5.0. While still largely relevant for later versions, there are some differences.
The third edition targets Lua 5.2 and is available at Amazon and other bookstores.
By buying the book, you also help to support the Lua project.


2.4 – Strings

Strings have the usual meaning: a sequence of characters. Lua is eight-bit clean and so strings may contain characters with any numeric value, including embedded zeros. That means that you can store any binary data into a string. Strings in Lua are immutable values. You cannot change a character inside a string, as you may in C; instead, you create a new string with the desired modifications, as in the next example:

    a = "one string"
    b = string.gsub(a, "one", "another")  -- change string parts
    print(a)       --> one string
    print(b)       --> another string

Strings in Lua are subject to automatic memory management, like all Lua objects. That means that you do not have to worry about allocation and deallocation of strings; Lua handles this for you. A string may contain a single letter or an entire book. Lua handles long strings quite efficiently. Programs that manipulate strings with 100K or 1M characters are not unusual in Lua.

We can delimit literal strings by matching single or double quotes:

    a = "a line"
    b = 'another line'
As a matter of style, you should use always the same kind of quotes (single or double) in a program, unless the string itself has quotes; then you use the other quote, or escape those quotes with backslashes. Strings in Lua can contain the following C-like escape sequences:

\abell
\bback space
\fform feed
\nnewline
\rcarriage return
\thorizontal tab
\vvertical tab
\\backslash
\"double quote
\'single quote
\[left square bracket
\]right square bracket

We illustrate their use in the following examples:

    > print("one line\nnext line\n\"in quotes\", 'in quotes'")
    one line
    next line
    "in quotes", 'in quotes'
    > print('a backslash inside quotes: \'\\\'')
    a backslash inside quotes: '\'
    > print("a simpler way: '\\'")
    a simpler way: '\'

We can specify a character in a string also by its numeric value through the escape sequence \ddd, where ddd is a sequence of up to three decimal digits. As a somewhat complex example, the two literals "alo\n123\"" and '\97lo\10\04923"' have the same value, in a system using ASCII: 97 is the ASCII code for a, 10 is the code for newline, and 49 (\049 in the example) is the code for the digit 1.

We can delimit literal strings also by matching double square brackets [[...]]. Literals in this bracketed form may run for several lines, may nest, and do not interpret escape sequences. Moreover, this form ignores the first character of the string when this character is a newline. This form is especially convenient for writing strings that contain program pieces; for instance,

    page = [[
    <HTML>
    <HEAD>
    <TITLE>An HTML Page</TITLE>
    </HEAD>
    <BODY>
     <A HREF="http://www.lua.org">Lua</A>
     [[a text between double brackets]]
    </BODY>
    </HTML>
    ]]
    
    write(page)

Lua provides automatic conversions between numbers and strings at run time. Any numeric operation applied to a string tries to convert the string to a number:

    print("10" + 1)           --> 11
    print("10 + 1")           --> 10 + 1
    print("-5.3e-10"*"2")     --> -1.06e-09
    print("hello" + 1)        -- ERROR (cannot convert "hello")
Lua applies such coercions not only in arithmetic operators, but also in other places that expect a number. Conversely, whenever it finds a number where it expects a string, Lua converts the number to a string:
    print(10 .. 20)        --> 1020
(The .. is the string concatenation operator in Lua. When you write it right after a numeral, you must separate them with a space; otherwise, Lua thinks that the first dot is a decimal point.)

Despite those automatic conversions, strings and numbers are different things. A comparison like 10 == "10" is always false, because 10 is a number and "10" is a string. If you need to convert a string to a number explicitly, you can use the function tonumber, which returns nil if the string does not denote a proper number:

    line = io.read()     -- read a line
    n = tonumber(line)   -- try to convert it to a number
    if n == nil then
      error(line .. " is not a valid number")
    else
      print(n*2)
    end

To convert a number to a string, you can call the function tostring or concatenate the number with the empty string:

    print(tostring(10) == "10")   --> true
    print(10 .. "" == "10")       --> true
Such conversions are always valid.