How to escape brackets in a multi-line string in Lua

Viewed 768

This is an exercise question from the book the lua programming language the 3th edition.

Exercise2.4: How can you embed the following piece of XML as a string in Lua?

Show at least two different ways.

Here is my answer:

 s = "<![CDATA\n  Hello world\n]]>"
 print(s)

 s2 = [[
 <![CDATA
    Hello world
  \]\]>
 ]]
 print(s2)

and the output:

<![CDATA
 Hello world
]]>
<![CDATA
 Hello world
\]\]>

Way 1 is right. The output of way 2 is not as expected. Without the backslash char, lua will show an error:

 lua: execrcise-4.1.lua:7: unexpected symbol near ']'

So I have a question, how to escape brackets in a multi-line string in Lua ?

My lua interpreter version is 5.4.2.

1 Answers

Actually the whole point of this exercise is that you find out how to solve this problem.

Ideally by reading the Lua manual.

There you'll learn that opening and closing brackets for long strings have levels.

Literal strings can also be defined using a long format enclosed by long brackets. We define an opening long bracket of level n as an opening square bracket followed by n equal signs followed by another opening square bracket. So, an opening long bracket of level 0 is written as [[, an opening long bracket of level 1 is written as [=[, and so on. A closing long bracket is defined similarly; for instance, a closing long bracket of level 4 is written as ]====]. A long literal starts with an opening long bracket of any level and ends at the first closing long bracket of the same level. It can contain any text except a closing bracket of the same level.

s2 = [[
 <![CDATA
    Hello world
  ]]>
 ]]

violates that bold rule as you close the long string prematurely leaving you with two extra brackets that cause a syntax error.

So what do you need to do if the string may not contain a closing bracket of level 0 ]] ? We increase the level of our long string.

s2 = [=[
 <![CDATA
    Hello world
  ]]>
 ]=]

You cannot escape a square bracket with a backslash in a Lua string btw. The only reason why you didn't get an error for the invalid escape sequence \] is that long strings ignore escape sequences.

Related