46

I'm trying to find out a way to use a multiline comment on a batch of code, but it keeps mistaking some syntax in it as a ]] and thinking I want it to end there, which I don't!

--[[
  for k,v in pairs(t) do
    local d = fullToShort[k]
    local col = xColours[v[1]] -- It stops here!
    cecho(string.format(("<%s>%s ", col, d))
  end
--]]

I thought I read somewhere it was possible to do use a different sort of combination to avoid those errors, like --[=[ or whatnot... Could someone help?

Jonathan Picazo
  • 975
  • 3
  • 13
  • 23

2 Answers2

73

As you can see in Strings tutorial there is a special [===[ syntax for nesting square braces. You can use it in block comments too. Just note, that number of = signs must be the same in open and close sequence.

For example 5 equals will work.

--[=====[ 
for k,v in pairs(t) do
   local d = fullToShort[k]
   local col = xColours[v[1]] -- It stops here!
   cecho(string.format(("<%s>%s ", col, d))
end
--]=====]
l2aelba
  • 21,591
  • 22
  • 102
  • 138
Seagull
  • 13,484
  • 2
  • 33
  • 45
  • 6
    That almost feels like a kludge. I wonder why they did it that way? – James Dec 18 '15 at 02:25
  • 13
    @James That's not a kludge - that's the only *right* way to do it. Every other fixed "magic comment closing character sequence" (henceforth MCCCS) fundamentally cannot cope with strings that contain the MCCCS itself. That's why you end up with [atrocities like `]]]]><![CDATA[>`](https://stackoverflow.com/a/223782/2707792) every single time you want to write `]]>` in `CDATA`. The only way to avoid it is to provide paired delimiters that can vary in length (or content, as in bash HEREDOCs). A much better question would have been: why don't all the other languages do it like Lua? – Andrey Tyukin Sep 02 '18 at 00:42
  • Cool, it also works when inserting a multine string between `[[` and `]]` inside a block comment. In this case, you can also put the `=` in the embedded block to distinguish it from the containing block boundaries, e.g. using `[=[` and `]=]` – hsandt Mar 01 '19 at 00:35
  • @AndreyTyukin OCaml solves the issue in an elegant way: comments must contain valid code tokens: `(* "*)" *)` works as well as `(* … (* nested comment *) ... *)`. It allows you to comment _any_ piece of syntaxically-valid code with no issue. – bfontaine Jan 05 '20 at 21:58
-3

You can use the following to create multiline comments past ]]'s:

--[[
   codes
]]
Mercury
  • 7,430
  • 3
  • 42
  • 54
miragessee
  • 313
  • 1
  • 4
  • 14