Ludicrous Software

Corona Quick Tip: Nested Block Comments

(Okay, this is really more of a Lua quick tip, but let’s not get nitpicky.)

This is one of those minor little syntactical things that are incredibly handy to know, but that are hard to remember if you don’t need it that often. Sometimes you may find that you would like to block comment out a chunk of code that already includes code that has been block commented. For example, in this code:

1
2
3
4
5
local foo = bar
--[[
local deltaX, deltaY = 57, 12
--]]
local temp = "hello"

Let’s say you wanted to temporarily comment out all of that code, without having to disturb the existing block comment. All you need to do is intersperse an equal sign in your brackets:

1
2
3
4
5
6
7
--[=[
local foo = bar
--[[
local deltaX, deltaY = 57, 12
--]]
local temp = "hello"
--]=]

(Unfortunately, the WordPress code syntax plugin I use doesn’t properly parse these kinds of block comments, but trust me, it works.)

If you want to, you can continue nesting comments by increasing the number of equal signs and square brackets, so the next levels would be [==[[foo]]==], [===[[[bar]]]===] and so on (not that you should).

The double square brackets are an alternative form of quotation marks. So really, all the square brackets do is convert the chunk of code into one long string literal; the initial comment marker (--) in front of the opening square brackets turns the entire chunk into essentially a very long single-line comment.

This also means that if you want to format long blocks of text (e.g. you’re generating html dynamically to display in a web popup and want the generated code to be easily readable), you can use square brackets and hard returns to your heart’s content. The returns and the spacing are maintained in the string, so you can use this format instead of inserting \n wherever you need a line break. For example:

1
2
3
4
5
6
local myLongString = [[This is one
     long string of text
     that is broken across many lines.
     Once again, pay no attention to the incorrect
     formatting.
     ]]