'Literals' section on the page about strings has broken examples

The page on strings has a section about Literals, linked here. This section is, put politely, bad.

It includes examples with no string delimiters and examples with no concatenation operator. It also includes examples that seem to make no sense at all, like in the Escape section where it shows this code:

print( String \abc\ )
print( "String with \" \\ and \ " )

The examples should be fixed so that they actually run.

9 Likes

I’ve re-written the Literals section how I believe it should be written. Any comments are warmly received.


Literals (or string literals) is simply the representation of a string.To specify we use bracket delimiters.

"" or '' or [[]]

In LUA any can be used, all have the same meaning though the quotes are generally used by convention.

Meaning we can specify a string like so:

s = "Hello"
s = 'Hello'
s = [[Hello]]

These are unpaired, whichever you open with you must close with. So not

"Hello' or 'Hello" 

If your string has quotes inside quotes you need to escape those quotes with a backslash.

print("He said \"Let's code properly please\"")

Though this can be avoided by using something like this:

print([[He said "Let's code properly please"]])

A backslash followed by certain letters has special meaning. (can be found in the LUA Manual) The most common of which is newline

s = "Hello, \nHow can I help?"

A backslash followed by the string.byte value of a character represents that character.

print( "\104\105" ) --will return hi

The square bracket pair is rather special in that it allows multi-line, does not interpret escape sequences and can be nested. This makes it useful for something like a HTML code block. In a multi-line string make sure to use equal signs to distinguish between the double brackets.

 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>
    ]==]

Multi-line literals can also be specified with a backslash at the end of each line.

s ="This\
string\
goes\
on\
and\
on"

You can concatenate using different symbols.

s = "Hello" .. [[ and goodbye]]
2 Likes

I agree, this section could use some work. I’ve created a ticket for this – thank-you @Allie_King for your helpful suggestions :slight_smile: