Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the point of nesting brackets in Lua?

Tags:

string

lua

I'm currently teaching myself Lua for iOS game development, since I've heard lots of very good things about it. I'm really impressed by the level of documentation there is for the language, which makes learning it that much easier.

My problem is that I've found a Lua concept that nobody seems to have a "beginner's" explanation for: nested brackets for quotes. For example, I was taught that long strings with escaped single and double quotes like the following:

string_1 = "This is an \"escaped\" word and \"here\'s\" another."

could also be written without the overall surrounding quotes. Instead one would simply replace them with double brackets, like the following:

string_2 = [[This is an "escaped" word and "here's" another.]]

Those both make complete sense to me. But I can also write the string_2 line with "nested brackets," which include equal signs between both sets of the double brackets, as follows:

string_3 = [===[This is an "escaped" word and "here's" another.]===]

My question is simple. What is the point of the syntax used in string_3? It gives the same result as string_1 and string_2 when given as an an input for print(), so I don't understand why nested brackets even exist. Can somebody please help a noob (me) gain some perspective?

like image 611
elersong Avatar asked Jan 21 '14 00:01

elersong


2 Answers

It would be used if your string contains a substring that is equal to the delimiter. For example, the following would be invalid:

string_2 = [[This is an "escaped" word, the characters ]].]]

Therefore, in order for it to work as expected, you would need to use a different string delimiter, like in the following:

string_3 = [===[This is an "escaped" word, the characters ]].]===]

I think it's safe to say that not a lot of string literals contain the substring ]], in which case there may never be a reason to use the above syntax.

like image 193
Tim Cooper Avatar answered Sep 17 '22 19:09

Tim Cooper


It helps to, well, nest them:

print [==[malucart[[bbbb]]]bbbb]==]

Will print:

malucart[[bbbb]]]bbbb

But if that's not useful enough, you can use them to put whole programs in a string:

loadstring([===[print "o m g"]===])()

Will print:

o m g

I personally use them for my static/dynamic library implementation. In the case you don't know if the program has a closing bracket with the same amount of =s, you should determine it with something like this:

local c = 0
while contains(prog, "]" .. string.rep("=", c) .. "]") do
  c = c + 1
end
-- do stuff
like image 27
jv110 Avatar answered Sep 19 '22 19:09

jv110